寫一個 JDBC 應用程式,骨架其實就是五個步驟:載入驅動、建立連線、送出 SQL、處理結果、收尾關閉。
用 java.lang.Class 的靜態方法 forName(String className) 把驅動類載入 JVM:
Class.forName("JDBC 驅動類名稱");
DriverManager 會跟著已註冊的驅動走:呼叫 getConnection() 時,它遍歷驅動列表,直到找到能連上連接字串所指資料庫的驅動,載入後建立連線。
Connection con = DriverManager.getConnection(資料庫連接字串, 資料庫用戶名, 密碼);
建立 Statement 實例,把 SQL 交給它所連的資料庫。Statement 有三類:
Statement。PreparedStatement。CallableStatement。Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from table1");
Statement 提供三種執行方法:
ResultSet executeQuery(String sqlString):執行查詢並回傳結果集。int executeUpdate(String sqlString):執行 INSERT、UPDATE、DELETE 以及 CREATE TABLE、DROP TABLE 等 DDL。boolean execute(String sqlString):執行會回傳多個結果集、多個更新計數或兩者混合的語句。ResultSet rs = stmt.executeQuery("SELECT * FROM ...");
int rows = stmt.executeUpdate("INSERT INTO ...");
boolean flag = stmt.execute(String sql);
分兩種情況:更新類語句回傳受影響的記錄數;查詢類語句回傳 ResultSet 物件。
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
操作完成後要關掉所有 JDBC 物件以釋放資源,關閉順序與宣告順序相反:結果集、聲明、連線。
if (rs != null) {
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
實務上這三段又臭又長的收尾常被抽成工具方法,或用 try-with-resources 讓編譯器代勞;但無論哪種寫法,「誰開的就要誰關」這條原則不變,否則連線池遲早被耗光。