DriverManager 內部靜態區塊可自動註冊驅動並同時管理多個驅動程式。本文展示如何設計一套「配置檔案指向配置檔案」的機制,讓切換資料庫只需修改一個主配置檔,無須動到程式碼。
src
└─ com.jdbc.java
├─ TestJDBC.java
└─ properties
├─ jdbcName.properties # 主配置:指定使用哪個資料庫配置
├─ mySql.properties # MySQL 連線資訊
└─ oracle.properties # Oracle 連線資訊(可擴充)
public Connection getConnection3() throws Exception {
String driverClass = null, jdbcUrl = null, user = null, password = null, jdbcName = null;
// 1. 讀取主配置,決定用哪個資料庫屬性檔
InputStream inStream = getClass().getClassLoader().getResourceAsStream("properties/jdbcName.properties");
Properties propName = new Properties();
propName.load(inStream);
jdbcName = propName.getProperty("jdbcName"); // 例如 "mySql"
// 2. 讀取對應的資料庫屬性檔
InputStream in = getClass().getClassLoader().getResourceAsStream("properties/" + jdbcName + ".properties");
Properties prop = new Properties();
prop.load(in);
driverClass = prop.getProperty("driver");
jdbcUrl = prop.getProperty("jdbcUrl");
user = prop.getProperty("user");
password = prop.getProperty("password");
// 3. 載入驅動並獲取連線(DriverManager 會自動管理已註冊驅動)
Class.forName(driverClass);
Connection conn = DriverManager.getConnection(jdbcUrl, user, password);
return conn;
}
# jdbcName.properties jdbcName=mySql # mySql.properties driver=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/test user=root password=123456 # oracle.properties(擴充範例) driver=oracle.jdbc.driver.OracleDriver jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl user=scott password=tiger
@Test
public void testGetConnection3() throws Exception {
System.out.println(getConnection3());
// 輸出:com.mysql.jdbc.JDBC4Connection@104a311
}