mysql之通過配置文件鏈接數據庫的示例詳解

這篇文章主要介紹了mysql 之通過配置文件鏈接數據庫的相關資料,主要是一個單例餓漢式的獲得數據庫連接方法工具類的實現,需要的朋友可以參考下

mysql 之通過配置文件鏈接數據庫

配置文件jdbc.properties

##MySQL  driver=com.mysql.jdbc.Driver  url=jdbc:mysql:///ake?useUnicode=true&characterEncoding=UTF-8  username=root  password=1234    ##Oracle  #driver=oracle.jdbc.driver.OracleDriver  #url=jdbc:oracle:thin:@127.0.0.1:1521:orcl  #username=scott  #password=tiger

簡單的講一下。配置文件寫了MySQL和Oracle的數據庫信息,我的數據庫是mysql 所以我把oracle的配置信息注釋掉了。

接下來就是一個單例(餓漢式)的獲得數據庫連接方法工具類

package?Studying.d15;    import?java.io.FileInputStream;  import?java.sql.Connection;  import?java.sql.DriverManager;  import?java.util.Properties;    public?class?ConnUtils?{  ??private?static?Connection?con?=?null;    ??static{  ????try?{  ??????Properties?p?=?new?Properties();  ??????p.load(?new?FileInputStream("jdbc.properties")?);  ??????String?driver?=?p.getProperty("driver");  ??????String?url?=?p.getProperty("url");  ??????String?username?=?p.getProperty("username");  ??????String?password?=?p.getProperty("password");  ??????System.out.println(url+","+driver);  ??????Class.forName(driver);  ??????con?=?DriverManager.getConnection(url,?username,?password);  ????}?catch?(Exception?e)?{  ??????e.printStackTrace();  ????}  ??}  ??public?static?Connection?getConnection(){  ????return?con;  ??}  }

? 版權聲明
THE END
喜歡就支持一下吧
點贊8 分享