1.新建c3p0.properties文件,放到src目录下,c3p0.properties文件样例
2.新建C3P0获取连接公共类
3.导入C3P0相关jar包
c3p0.jdbcUrl=jdbc:oracle:thin:@127.0.0.1:1521:orcl
c3p0.driverClass=oracle.jdbc.driver.OracleDriver
c3p0.user=test
c3p0.password=test
c3p0.acquireIncrement=3
c3p0.idleConnectionTestPeriod=60
c3p0.initialPoolSize=10
c3p0.maxIdleTime=60
c3p0.maxPoolSize=20
c3p0.maxStatements=100
c3p0.minPoolSize=5
2.新建C3P0获取连接公共类
public class MyC3P0Utils{
private static DataSource ds;
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
static {
ds = new ComboPooledDataSource();//直接使用即可,不用显示的配置,其会自动识别配置文件
}
public static DataSource getDataSource() {
return ds;
}
public static Connection getConnection() {
try {
// 得到当前线程上绑定的连接
Connection conn = tl.get();
if (conn == null) { // 代表线程上没有绑定连接
conn = ds.getConnection();
tl.set(conn);
}
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void startTransaction() {
try {
// 得到当前线程上绑定连接开启事务
Connection conn=getConnection();
conn.setAutoCommit(false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void commitTransaction() {
try {
Connection conn = tl.get();
if (conn != null) {
conn.commit();
}
} 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容器中移除对应当前线程的链接)
}
}
}
3.导入C3P0相关jar包