package jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
public static String driver;
public static String url;
public static String user;
public static String password;
// 利用静态初始化块进行初始化操作
static { // 静态初始化块在类加载时执行
try (
// 1. 通过类加载器读取配置文件
// 1.1 通过类加载器获取配置文件的输入流
InputStream is = JDBCUtils.class.getClassLoader()
.getResourceAsStream("db.propeties");
) {
// 1.2 创建 Properties 对象
Properties prop = new Properties();
// 1.3 加载“配置文件”输入流
prop.load(is);
// 2. 执行初始化操作
driver = prop.getProperty("driver");
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
// 3. 加载 MySQL 数据库驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取数据库连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
// 释放 Connection、Statement 和 ResultSet 资源
// 这里也可以不写释放资源的两个方法,直接使用try-with-resource语句释放资源
// 将Connection、Statement 和 ResultSet 对象的创建放在 try 后面的小(圆)括号中
public static void closeAll(Connection conn, Statement stmt, ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
// 在方法体中调用本类的另一个方法时,可以省略写 this
close(conn, stmt);
}
// 重载 close 方法
public static void close(Connection conn, Statement stmt) throws SQLException {
if (conn != null) {
conn.close();
}
if (stmt != null) {
stmt.close();
}
}
}
JDBCUtils工具类的书写
于 2022-05-24 16:24:12 首次发布