package com.jiamian.furns.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* @author 韩顺平
* @version 1.0
* 基于druid数据库连接池的工具类
*/
public class JDBCUtilsByDruid {
private static DataSource ds;
public static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
//在静态代码块完成 ds初始化
static {
Properties properties = new Properties();
try {
//因为这里是web项目,它的工作目录是out,文件加载,需要使用类加载器
//properties.load(new FileInputStream("src\\druid.properties"));
properties.load(JDBCUtilsByDruid.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//编写getConnection方法
public static Connection getConnection() throws SQLException {
Connection conn = threadLocal.get();
if (conn == null) {
conn = ds.getConnection();
//设置手动提交, 事务管理需要
conn.setAutoCommit(false);
threadLocal.set(conn);
}
return conn;
}
//提交事务
public static void commit() {
Connection connection = threadLocal.get();
if (connection != null) {
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}finally {
//关闭连接
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//说明
//1. 当提交后,需要把connection从 threadLocalConn 清除掉
//2. 不然,会造成 threadLocalConn 长时间持有该连接, 会影响效率
//3. 也因为我们Tomcat底层使用的是线程池技术
threadLocal.remove();
}
//回滚事务
public static void rollback() {
Connection connection = threadLocal.get();
if (connection != null) {
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
threadLocal.remove();
}
//关闭连接, 老师再次强调: 在数据库连接池技术中,close 不是真的断掉连接
//而是把使用的Connection对象放回连接池
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
基于druid数据库连接池的工具类第二版(事务管理版)
最新推荐文章于 2024-09-01 13:09:09 发布