给你一个c3p0的连接池
c3p0.properties 配置文件
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/market
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.user=root
c3p0.password=root
c3p0.acquireIncrement=3
c3p0.idleConnectionTestPeriod=60
c3p0.initialPoolSize=10
c3p0.maxIdleTime=60
c3p0.maxPoolSize=20
c3p0.maxStatements=100
c3p0.minPoolSize=5
代码 我这是java代码
package com.senter.util;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Utils {
private static DataSource ds;
private static ThreadLocal tl = new ThreadLocal(); // map
static {
ds = new ComboPooledDataSource();// 直接使用即可,不用显示的配置,其会自动识别配置文件
}
public static DataSource getDataSource() {
return ds;
}
public static Connection getConnection() throws SQLException {
Connection conn = tl.get();
try {
if (conn == null) {
// 代表线程上没有绑定连接
conn = ds.getConnection();
tl.set(conn);
}
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException(e);
}
return conn;
}
public static void startTransaction() {
try {
// 得到当前线程上绑定连接开启事务
Connection conn = tl.get();
if (conn == null) { // 代表线程上没有绑定连接
conn = ds.getConnection();
tl.set(conn);
}
conn.setAutoCommit(false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void closeConnection() {
try {
Connection conn = tl.get();
if (conn != null) {
conn.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
tl.remove(); // 千万注意,解除当前线程上绑定的链接(从threadlocal容器中移除对应当前线程的链接)
}
}
}