基於屬性文件配置的連接池雛形,封裝資源獲取、釋放、通用更新三大核心能力。
public class JDBCTools {
// 雙層配置:jdbcName.properties 指定當前環境,對應具體 db.properties
public static Connection getConnection() throws Exception {
// 1. 讀取 jdbcName.properties 獲取環境標識
// 2. 讀取對應 db.properties 獲取 driver、url、user、password
// 3. Class.forName(driver) 註冊驅動
// 4. DriverManager.getConnection(url, user, password)
return connection;
}
// 安全釋放資源,順序:Statement → Connection
public static void release(Statement stmt, Connection conn) {
if (stmt != null) try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
if (conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
# properties/jdbcName.properties
jdbcName=mysql_dev
# properties/mysql_dev.properties
driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf8
user=dev
password=dev123
public void update(String sql) {
Connection conn = null;
Statement stmt = null;
try {
conn = JDBCTools.getConnection();
stmt = conn.createStatement();
stmt.executeUpdate(sql); // 支持 INSERT/UPDATE/DELETE
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.release(stmt, conn); // 保證資源釋放
}
}
| 痛點 | 優化方案 |
|---|---|
| 頻繁創建連接開銷大 | 引入 Druid/HikariCP 連接池,替換 getConnection 實現 |
| SQL 注入風險 | 改用 PreparedStatement + 參數綁定 |
| 事務控制缺失 | 添加 Connection.setAutoCommit(false) + commit/rollback |
| 異常吞噬 | 拋出自定義異常或返回 Result 對象,避免 printStackTrace 丟失上下文 |
public void updateWithParams(String sql, Object... params) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCTools.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
ps.executeUpdate();
} finally {
JDBCTools.release(ps, conn);
}
}
// 調用
updateWithParams("INSERT INTO users(name, email) VALUES(?, ?)", "張三", "zhangsan@example.com");
此模板為後續引入連接池、ORM 框架奠定基礎,理解其資源管理本質至關重要。