c3p0使用

1.导入jar包

2.在src下创建c3p0-config.xml配置文件(c3p0的配置文件既可以是properties文件也可以是xml文件)

<xml version="1.0" encoding="UTF-8">

<c3p0-config>
<!-- 默认配置,如果没有指定则使用这个配置 -->
<default-config>
<property name="user">root</property>
<property name="password">dimples</property>
<property name="jdbcUrl">jdbc:mysql://47.106.102.235:3306/bysj_zdc</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="initialPoolSize">3</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">2</property>
<property name="maxStatements">200</property>
</default-config>
<!-- 命名的配置,可以通过方法调用实现 -->
<named-config name="zdc">
<property name="user">root</property>
<property name="password">dimples</property>
<property name="jdbcUrl">jdbc:mysql://47.106.102.235:3306/bysj_zdc</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- 如果池中数据连接不够时一次增长多少个 -->
<property name="acquireIncrement">5</property>
<!-- 初始化数据库连接池时连接的数量 -->
<property name="initialPoolSize">20</property>
<!-- 数据库连接池中的最大的数据库连接数 -->
<property name="maxPoolSize">25</property>
<!-- 数据库连接池中的最小的数据库连接数 -->
<property name="minPoolSize">5</property>
</named-config>
</c3p0-config>

</xml>

3.创建c3p0工具类

package c3p0;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {

//加载默认配置
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
//加载自定义配置
//private static ComboPooledDataSource dataSource = new ComboPooledDataSource("zdc");

public static DataSource getDataSource(){
return dataSource;
}

//使用try/catch而不是throws是因为工具类被其它方法调用时,调用者都会进行异常处理,而try/catch只需处理一次
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

原文地址:https://www.cnblogs.com/Life-is-Demo/p/10889918.html