java連接mysql數據庫-從配置文件中讀取


本章內容:從配置文件中讀取配置,連接數據庫
1.maven jdbc的jar包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>

2.編寫讀取連接數據庫的方法
public boolean connection(){
boolean success=false;
//定義要讀取的字段
String driver=null;
String url=null;
String username=null;
String password=null;
Connection conn=null;

try {
//從配置文件中讀取配置
Properties properties=new Properties();
//獲取配置文件的路徑
String path=Thread.currentThread().getContextClassLoader().getResource("jdbc.properties").getPath();
FileInputStream in=null;
in=new FileInputStream(path);
properties.load(in);
System.out.println("path:"+path);
//獲取配置文件中的信息,放入到對應的變量中
driver=properties.getProperty("driver");
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password");
System.out.println("獲取到的URL:"+url+"\t username:"+username+"\tpassword:"+password);
in.close();
//加載驅動
Class.forName(driver);
System.out.println("開始連接數據庫!");
conn = DriverManager.getConnection(url, username, password);//連接數據庫
if (!(conn==null)){
success=true;
System.out.println("連接數據庫成功");
}else {
success=false;
System.out.println("連接數據庫失敗!");
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return success;
}

配置文件jdbc.properties如下
driver =com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false
username=root
password=123456

適合小白學習,如有不對,歡迎指正提出



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM