JDBC 核心流程:取得連線 → 建立 Statement → 執行 SQL → 處理結果 → 關閉資源。本文聚焦三大進階技巧,提升效能與資料一致性。
// 僅捲動、唯讀
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, // 不反映他人變更
ResultSet.CONCUR_READ_ONLY);
// 可捲動、可更新
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, // 即時反映他人變更
ResultSet.CONCUR_UPDATABLE);
// PreparedStatement 同理
PreparedStatement ps = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
// 定位第 9000 列
rs.absolute(9000);
TYPE_SCROLL_INSENSITIVE:快照模式,效能較好。TYPE_SCROLL_SENSITIVE:動態模式,支援 rs.updateRow()、insertRow()、deleteRow() 直接操作資料庫。Statement stmt = conn.createStatement();
stmt.addBatch("INSERT INTO t VALUES (1,'a')");
stmt.addBatch("UPDATE t SET c='b' WHERE id=2");
stmt.addBatch("DELETE FROM t WHERE id=3");
int[] counts = stmt.executeBatch(); // 每條影響列數
PreparedStatement ps = conn.prepareStatement("INSERT INTO t (id,name) VALUES (?,?)");
for (int i=1; i<=1000; i++) {
ps.setInt(1, i);
ps.setString(2, "name"+i);
ps.addBatch();
}
int[] counts = ps.executeBatch(); // 單次網路往返完成 1000 筆插入
conn.setAutoCommit(false) 手動提交,再 conn.commit(),避免單條自動提交產生大量交易記錄。conn.setAutoCommit(false); // 關閉自動提交
try {
Statement stmt = null;
// 業務邏輯 1
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO users ...");
stmt.close();
// 業務邏輯 2
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO corps ...");
stmt.close();
conn.commit(); // 全部成功才提交
} catch (SQLException e) {
conn.rollback(); // 任一失敗全盤回滾
throw e;
} finally {
conn.setAutoCommit(true); // 恢復預設
}
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
建議使用 try-with-resources (Java 7+) 自動管理。