LoslegenKostenlos loslegen

Setting up the connection

CityBook Libraries needs your application to establish a live connection to their PostgreSQL database. You'll use JDBC's DriverManager.getConnection() method to open the connection, passing in the URL, username, and password.

To ensure proper resource management, you'll wrap the connection in a try-with-resources block so it closes automatically. The Credentials class with URL, USER, and PASSWORD fields is already available, along with the necessary imports: Connection, DriverManager, and SQLException.

Diese Übung ist Teil des Kurses

Querying a PostgreSQL Database in Java

Kurs anzeigen

Anleitung zur Übung

  • Enclose the connection in a try block.
  • Create a connection from DriverManager.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

public class Main {
    public static void main(String[] args) throws SQLException {
        // Open a connection using try-with-resources
        ____ (Connection conn = ____.____(Credentials.URL, Credentials.USER, Credentials.PASSWORD)) {
            System.out.println("Connected to the database!");
        }
    }
}
Code bearbeiten und ausführen