C3P0连接池配置(C3P0Utils.java)
配置文件 c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/db?useSSL=true</property> <property name="user">root</property> <property name="password">123456</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">20</property> </default-config> <named-config name="mysqlConn"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/db?useSSL=true</property> <property name="user">root</property> <property name="password">123456</property> </named-config> </c3p0-config>
C3P0连接池工具类 C3P0Utils.java
package top.try51.utils; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Utils { // 加载名称为mysqlConn 的配置(src下放置 c3p0-config.xml 配置文件) //private static ComboPooledDataSource ds = new ComboPooledDataSource();//默认配置项 //private static ComboPooledDataSource ds = new ComboPooledDataSource("mysqlConn");//指定名称的配置项 private static ComboPooledDataSource ds = new ComboPooledDataSource("sqlServerConn");//指定名称的配置项 /** * 定义一个ThreadLocal,绑定Connection,每个线程对应一个Connection,执行事务使用 */ private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); /** * * @return ComboPooledDataSource */ public static DataSource getDataSource() { return ds; } /** * * @return 由DataSource创建的 Connection */ public static Connection getConnection() { try { return ds.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } } /** * * @return 获取当前线程绑定的Connection * @throws SQLException */ public static Connection getTranConnection() throws SQLException{ //得到ThreadLocal中的connection Connection conn = tl.get(); //判断conn是否为空,如果不为空,则说明事务已经开启 if(conn == null){ conn = getConnection(); //把当前开启的事务放入ThreadLocal中 tl.set(conn); } return conn; } /** * 开启事务,如果当前线程中没有Connection,则创建该线程对应的一个Connection * @throws SQLException */ public static void beginTran() throws SQLException { //设置事务提交为手动 getTranConnection().setAutoCommit(false); } /** * 提交事务 * @throws SQLException */ public static void commit() throws SQLException { //得到ThreadLocal中的connection Connection conn = getTranConnection(); //判断conn是否为空,如果为空,则说明没有开启事务 if(conn != null){ //如果conn不为空,提交事务 conn.commit(); //事务提交后,关闭连接 conn.close(); //将连接移出ThreadLocal tl.remove(); } } /** * 回滚事务 * @throws SQLException */ public static void rollback() throws SQLException { //得到ThreadLocal中的connection Connection conn = getTranConnection(); //判断conn是否为空,如果为空,则说明没有开启事务,也就不能回滚事务 if(conn != null){ //事务回滚 conn.rollback(); //事务回滚后,关闭连接 conn.close(); //将连接移出ThreadLocal tl.remove(); } } }