在 JDBC 資料庫操作中,save 方法缺少異常處理與資源釋放程式碼,導致程式碼不完整且存在資源洩漏風險。
public int save(Users users) {
int i = 0;
con = DatabaseDAO.getConnection();
try {
pt = con.prepareStatement("insert into users(...) values(?,?,...)");
// 設定參數...
i = pt.executeUpdate();
return i; // 直接返回,缺少 catch 與 finally
}
}
public int save(Users users) {
int i = 0;
Connection con = null;
PreparedStatement pt = null;
try {
con = DatabaseDAO.getConnection();
pt = con.prepareStatement("insert into users(...) values(?,?,...)");
// 設定參數...
i = pt.executeUpdate();
return i;
} catch (SQLException e) {
e.printStackTrace(); // 記錄異常堆疊
// 可拋出自定義異常或返回錯誤碼
throw new RuntimeException("資料庫操作失敗", e);
} finally {
// 確保資源關閉,避免洩漏
DatabaseDAO.closePt(pt);
DatabaseDAO.closeCon(con);
}
}
SQLException 而非通用 ExceptionResultSet → Statement → Connectionpublic int save(Users users) {
String sql = "insert into users(...) values(?,?,...)";
try (Connection con = DatabaseDAO.getConnection();
PreparedStatement pt = con.prepareStatement(sql)) {
// 設定參數...
return pt.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException("資料庫操作失敗", e);
}
// 自動關閉資源,無需 finally
}
| 錯誤做法 | 正確做法 |
|---|---|
| catch 區塊為空 | 至少記錄日誌或拋出異常 |
| finally 中未關閉資源 | 完整關閉所有 JDBC 資源 |
| 關閉資源順序錯誤 | 遵循 ResultSet → Statement → Connection |
| 連線未在 finally 關閉 | 確保連線歸還連線池 |
完整的 JDBC 操作必須包含:獲取連線 → 預編譯 SQL → 設定參數 → 執行 → 異常處理 → 資源釋放。使用 Try-with-resources 可大幅簡化代碼並提高安全性。