作为一个JDBCUtil标准工具类,是一个很好用的工具。
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtil{
// 就读一个配置文件 直接先定义再使用
private static final Properties properties = new Properties();
// 通过ThreadLocal容器实现事务 原理 一个事务获取一个链接 不同事务获取不同链接
private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
// 静态加载块
static {
// 监视领域
try {
// 因为一个JDBC只连接一个数据库,所以 数据库连接的加载文件只用加载一次即可,无需重复
InputStream in = JDBCUtil.class.getResourceAsStream("/conn/baizhi/my.properties");
properties.load(in);
// 读入文件后,就可以把输入流关闭 比较节省资源 减少不必要的bug
in.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("my.properties文件加载失败/输入流关闭失败",e);
}
}
// 通过读取文件 已经获取了所有信息此类均共享 只要在此用方法返回即可
public static Connection getConnection() {
// 通过容器拿到链接 若有就不再给新的 保证一个事物 一个链接 容器的get方法 可以获取容器内的链接
Connection connection = threadLocal.get();
// 判断是否为空 如果是空的 那么重新建立 不为空 则直接返回
if (connection == null) {
try {
// 重新建立的步骤
// 类加载的第一种写法 获取字符串 再使用Class.forName(driver);
String driver = properties.getProperty("mydriver");
Class.forName(driver);
// 孔乙己 类加载的第二种写法 此种方法不再需要 my.properties提供第一行数据 下面已经使用了完整类(包加类)
//com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();
//DriverManager.registerDriver(driver);
// 因为之前已经将文本信息读到properties里 在此处只需要不停使用 getProperty 用映射获取值即可
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
// 通过上述方法后获取实质上的链接
connection = DriverManager.getConnection(url,username,password);
// 获取链接后 装在容器里
threadLocal.set(connection);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("驱动类加载失败",e);
}
}
// 不论是容器内的链接也好 还是新建的也好 只要返回即可
return connection;
}
// 关闭连接 三种链接 本质上是为了方便 其他类
public static void close(ResultSet rs, PreparedStatement pstm, Connection conn) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("结果集关闭失败", e);
}
try {
if (pstm != null) {
pstm.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("发送sql工具PreparedStatement关闭失败", e);
}
try {
if (conn != null) {
conn.close();
threadLocal.remove();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("链接Connection关闭失败", e);
}
}
// 增加代码健壮性 重写增强了它的功能 可以专门负责处理 增删改
public static void close(PreparedStatement pstm, Connection conn){
close(null,pstm,conn);
}
// 增加代码健壮性 重写增强了它的功能 可以专门负责处理 dao类的增删改
public static void close(PreparedStatement pstm){
close(null,pstm,null);
}
}