優點:
- 便於修改連接屬性。只需在配置文件中修改,不需要在代碼中修改了。
- 更易於維護代碼安全性。
方法:
- 在src文件嘉下創建database.properties文本文件;添加內容:
driver = com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/y1 name=root password=root
- 創建工具類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+"數據庫連接失敗");
}
}
public static Connection getConnection(){
return con;
}
- 其他類使用時調用即可
Connection con = MyJDBCUtiles.getConnection();
System.out.println(con);
- 輸出結果

完美^_^
