為什么使用配置文件: 使用配置文件可以解耦合,更改數(shù)據(jù)庫信息不需要重新編譯部署
一.準備配置文件
配置文件簡單示例: 配置文件后綴為 .properties 例如: jdbc.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/myself
user=root
password=root
二. 引入配置文件 并獲取配置信息
注意 自己的配置文件路徑是否在當(dāng)前包下
ResourceBundle bundle = ResourceBundle.getBundle("com.study.jdbc.jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
三.完整JAVA代碼示例:
package com.study.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class JDBCTest01 {
public static void main(String[] args) {
Connection conn = null;
// 讀取屬性配置文件, 獲取數(shù)據(jù)庫信息
ResourceBundle bundle = ResourceBundle.getBundle("com.study.jdbc.jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
try {
// 加載數(shù)據(jù)庫驅(qū)動類
Class.forName(driver);
// 建立數(shù)據(jù)庫連接
conn = DriverManager.getConnection(url, user, password);
// 打印連接對象,驗證連接是否成功
System.out.println(conn);
} catch (SQLException e) {
// 處理 SQL 異常
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
// 處理驅(qū)動類未找到異常
throw new RuntimeException(e);
} finally {
// 確保在程序結(jié)束時關(guān)閉數(shù)據(jù)庫連接
if (conn != null) {
try {
// 關(guān)閉數(shù)據(jù)庫連接
conn.close();
} catch (SQLException e) {
// 處理關(guān)閉連接時可能發(fā)生的 SQL 異常
throw new RuntimeException(e);
}
}
}
}
}