一、C3P0配置
1、使用xml方式(名称为c3p0-config.xml)
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/tv_guide
</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
</c3p0-config>
2、使用properties方式(名称为c3p0.properties)
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/tv_guide
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
二、C3P0的使用
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<Connection> tl = new ThreadLocal<Connection>(); // map
static {
ds = new ComboPooledDataSource();//直接使用即可,不用显示的配置,其会自动识别配置文件
}
public static DataSource getDataSource() {
return ds;
}
public static Connection getConnection() throws SQLException {
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 = tl.get();
if (conn == null) { // 代表线程上没有绑定连接
conn = ds.getConnection();
tl.set(conn);
}
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容器中移除对应当前线程的链接)
}
}
}
详细信息见:http://www.mchange.com/projects/c3p0/c3p0官方网站