統一工具類設計
package com.cai.jdbc;
import java.sql.*;
import java.util.Properties;
public class ConnectionUtil {
// 模式 1:方法內硬編碼(僅供測試/演示)
public Connection getConnection() {
return getConnection(
"com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/stud",
"root", "root"
);
}
// 模式 2:參數傳遞(靈活但調用處耦合配置)
public Connection getConnection(String driver, String url, String user, String pwd) {
try {
Class.forName(driver);
return DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
throw new RuntimeException("獲取連接失敗", e);
}
}
// 模式 3:Properties 文件外部化(生產推薦)
public Connection openConnection() {
Properties props = new Properties();
try (InputStream in = getClass().getClassLoader()
.getResourceAsStream("DBConfig.properties")) {
props.load(in);
String driver = props.getProperty("driver");
String url = props.getProperty("url");
String user = props.getProperty("user");
String pwd = props.getProperty("password");
Class.forName(driver);
return DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
throw new RuntimeException("加載配置失敗", e);
}
}
}
DBConfig.properties 示例
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/stud
user=root
password=root
三種模式對比
| 模式 | 優點 | 缺點 | 適用場景 |
| 硬編碼 | 簡單直接 | 重新編譯才能改配置,密碼明文入庫 | 單元測試、快速原型 |
| 參數傳遞 | 運行期動態決定 | 調用鏈層層透傳,配置分散 | 多數據源動態切換 |
| Properties 文件 | 配置與代碼分離,易維護、易加密 | 需約定文件路徑/命名 | 生產環境標準做法 |
生產級增強建議
- 引入連接池:HikariCP / Druid / DBCP2,替換
DriverManager
- 配置加密:密碼字段 AES 加密,讀取時解密
- 多環境隔離:
DBConfig-dev.properties / DBConfig-prod.properties,啟動參數指定
- 資源關閉:使用
try-with-resources 自動歸還連接
測試主程序
public static void main(String[] args) {
ConnectionUtil cu = new ConnectionUtil();
System.out.println("1. 硬編碼: " + cu.getConnection());
System.out.println("2. 參數傳遞: " + cu.getConnection("driver","url","user","pwd"));
System.out.println("3. Properties: " + cu.openConnection());
}