Zacznij terazZacznij za darmo

Connection management

Database connections are expensive resources that must be closed properly to avoid memory leaks. Java's try-with-resources syntax automatically closes connections, statements, and result sets when the block completes, even if errors occur.

Ensure CityBook Libraries' application manages resources safely.

To ćwiczenie jest częścią kursu

Querying a PostgreSQL Database in Java

Zobacz kurs

Instrukcje do ćwiczenia

  • Wrap resources in a try-with-resources block.
  • Add exception handling for database errors.

Interaktywne ćwiczenie praktyczne

Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.

public class Main {
    public static void main(String[] args) {
        // Use try-with-resources for automatic cleanup
        ____ (Connection conn = DriverManager.getConnection(Credentials.URL, Credentials.USER, Credentials.PASSWORD);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM books")) {
            while (rs.next()) {
                System.out.println(rs.getString("title"));
                System.out.println(rs.getInt("publication_year"));
            }
        // Handle database exceptions
        } ____ (SQLException e) {
            System.out.println("Error: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
        }
    }
}
Edytuj i uruchom kod