/**
 * DatabaseExample - Basic database query
 * This example demonstrates how to query a SQLite database.
 *
 * Part of Part III of the book "Introduction to Programming in Java"
 *
 * Requirement: The database must be created first with CreateDatabase.java
 */

import java.sql.*;

public class DatabaseExample {

    private static final String DB_URL = "jdbc:sqlite:restaurants.db";

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // Establish a connection to the database
            connection = DriverManager.getConnection(DB_URL);
            System.out.println("Connection established with the database.");

            // Create a statement
            statement = connection.createStatement();

            // Execute a query
            String sql = "SELECT id, name, price_range, area, rating FROM restaurants";
            resultSet = statement.executeQuery(sql);

            // Process the results
            System.out.println("\nRestaurants:");
            System.out.println("ID | Name | Price Range | Area | Rating");
            System.out.println("--------------------------------------------------");

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String priceRange = resultSet.getString("price_range");
                String area = resultSet.getString("area");
                double rating = resultSet.getDouble("rating");

                System.out.printf("%d | %s | %s | %s | %.1f%n", id, name, priceRange, area, rating);
            }

        } catch (SQLException e) {
            System.err.println("Error accessing the database: " + e.getMessage());
        } finally {
            // Close resources
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
                System.out.println("\nConnection closed.");
            } catch (SQLException e) {
                System.err.println("Error closing connection: " + e.getMessage());
            }
        }
    }
}
