1.所需要的jar包
https://mvnrepository.com/artifact/com.mchange/c3p0
https://mvnrepository.com/artifact/com.mchange/mchange-commons-java/0.2.15
2.配置c3p0-config.xml文件 放在src文件夾下
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <!-- 默認配置 --> <default-config> <!-- 連接參數 --> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/Manager</property> <property name="user">root</property> <property name="password">root</property> <!-- 連接池參數 --> <!-- 初始化申請的連接數量 --> <property name="initialPoolSize">5</property> <!-- 最大的連接數量 --> <property name="maxPoolSize">10</property> <!-- 超時時間 --> <property name="checkoutTimeout">3000</property> </default-config> <!--c3p0配置1--> <named-config name="c3p0"> <!-- 連接參數 --> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/manager</property> <property name="user">root</property> <property name="password">root</property> <!-- 連接池參數 --> <property name="initialPoolSize">5</property> <property name="maxPoolSize">8</property> <property name="checkoutTimeout">1000</property> </named-config> </c3p0-config>
3.配置c3p0數據源工具類
public class ComboPooledDataSourceUtil {
private static ComboPooledDataSource dataSource =new ComboPooledDataSource("c3p0");
//xml編碼 public static DataSource getDataSourceByxml(){
return dataSource;
} }
4.測試
@Test //測試c3p0 public void test_c3p0() throws PropertyVetoException, SQLException { Connection connection = ComboPooledDataSourceUtil.getDataSourceByxml().getConnection(); //Connection connection = ComboPooledDataSourceUtil.getDataSource().getConnection(); System.out.println(connection); }