连接数据库工具类:DBUtil.java
package util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/*
* @param null:
* jdbc连接工具类
* @return null
* @author liu
* @description TODO
* @date 2024/5/25 17:05
*/
public class DBUtil {
private static Connection con;
private static final String driver;
private static String url;
private static String username;
private static String password;
static{
// 读取数据库连接配置文件 反射机制加载类下资源
InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
try {
// 加载输入流文件内容
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
// 连接方法