java通過配置檔案載入資料庫(以Mysql為例)
阿新 • • 發佈:2019-01-30
專案結構如圖示
jdbc.properties內容為:
jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8
新建一個util包,用來存放工具類
新建DBUtil類
1.定義所需靜態欄位
2.新增載入配置的方法loadConfig()private static String username; private static String password; private static String url; private static String driver;
private static void loadConfig(){//載入配置資訊
try {
//兩種方法獲取配置檔案輸入流資訊
InputStream inStream = DBUtil.class
.getResourceAsStream("/jdbc.properties");//1.通過類載入器獲取具有給定名稱的資源,以‘/’開始,絕對資源名為/後面的一部分
相關錯誤問題解析://InputStream inStream=new BufferedInputStream(new FileInputStream("src/jdbc.properties"));//2.同一方法獲取的檔案的輸入流
Properties properties=new Properties();// 建立一個空屬性列表例項,Properties 可儲存在流中或從流中載入 properties.load(inStream);//從輸入流中讀取屬性列表(鍵和元素對) username=properties.getProperty("jdbc.username");//配置資訊 password=properties.getProperty("jdbc.password"); driver=properties.getProperty("jdbc.driver"); url=properties.getProperty("jdbc.url"); Class.forName(driver); } catch (Exception e) { throw new RuntimeException("操作配置屬性檔案異常",e); } }
在獲取配置檔案時可能無法獲取到,但是丟擲的是空指標異常,究其原因是未獲取輸入流的資料,即InputStream所獲取的配置檔案資訊,此時應當明確自己構建的配置檔案的路徑是否與程式碼內載入的路徑
getResourceAsStream("/jdbc.properties")
是否不符。3.通過靜態程式碼塊來載入方法
static{
loadConfig();//載入配置資訊} 4.構建連線方法
public static Connection getConnection(){
Connection conn=null;
try {
conn = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}