開始使用免費開始

設定連線

CityBook Libraries 需要你的應用程式與他們的 PostgreSQL 資料庫建立即時連線。你將使用 JDBC 的 DriverManager.getConnection() 方法開啟連線,並傳入 URL、使用者名稱與密碼。

為了妥善管理資源,你會把連線包在 try-with-resources 區塊中,讓它自動關閉。Credentials 類別已提供 URLUSERPASSWORD 欄位,且必要的匯入:ConnectionDriverManagerSQLException 也都已可用。

本練習屬於課程

在 Java 中查詢 PostgreSQL 資料庫

檢視課程

練習說明

  • 將連線包在 try 區塊中。
  • DriverManager 建立連線。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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!");
        }
    }
}
編輯並執行程式碼