處理資料庫例外
資料庫操作可能因多種原因失敗:資料表可能不存在、欄位名稱可能拼錯,或連線可能中斷。JDBC 會使用 SQLException 來捕捉這些錯誤,並提供錯誤訊息與 SQL 狀態碼等詳細資訊。
本練習中的查詢刻意包含拼字錯誤(使用 boks 而非 books)。
本練習屬於課程
在 Java 中查詢 PostgreSQL 資料庫
練習說明
- 在查詢失敗時擷取例外。
- 從例外中印出錯誤訊息與 SQLState。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class Main {
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection(Credentials.URL, Credentials.USER, Credentials.PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM boks")) {
while (rs.next()) {
System.out.println(rs.getString("title"));
System.out.println(rs.getInt("publication_year"));
}
// Catch database exceptions
} catch (____ e) {
// Print the error message and SQLState
System.out.println("Error: " + e.____());
System.out.println("SQLState: " + e.____());
}
}
}