基于Properties實現(xiàn)配置數(shù)據(jù)庫驅動
更新時間:2020年05月06日 11:19:12 作者:YouLan
這篇文章主要介紹了基于Properties實現(xiàn)配置數(shù)據(jù)庫驅動,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
優(yōu)點:
便于修改連接屬性。只需在配置文件中修改,不需要在代碼中修改了。 更易于維護代碼安全性。
方法:
在src文件嘉下創(chuàng)建database.properties文本文件;添加內容:
driver = com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/y1
name=root
password=root
創(chuàng)建工具類MyJDBCUtiles.java,添加代碼:
package com.kong.JDBCUtils;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class MyJDBCUtiles {
private MyJDBCUtiles(){}
private static Connection con;
private static String driver;
private static String url;
private static String name;
private static String password;
static{
try {
InputStream is = MyJDBCUtiles.class.getClassLoader().getResourceAsStream("database.properties");
Properties properties = new Properties();
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
name = properties.getProperty("name");
password = properties.getProperty("password");
Class.forName(driver);
con = DriverManager.getConnection(url, name, password);
}catch (Exception ep){
throw new RuntimeException(ep+"數(shù)據(jù)庫連接失敗");
}
}
public static Connection getConnection(){
return con;
}
其他類使用時調用即可
輸出結果

完美^_^
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關文章
SpringBoot中TypeExcludeFilter的作用及使用方式
在SpringBoot應用程序中,TypeExcludeFilter通過過濾特定類型的組件,使它們不被自動掃描和注冊為bean,這在排除不必要的組件或特定實現(xiàn)類時非常有用,通過創(chuàng)建自定義過濾器并注冊到spring.factories文件中,我們可以在應用啟動時生效2025-01-01

