package com.c3p0;
import java.sql.Connection;
import javax.sql.DataSource;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBC {
private static DataSource dataSource = null;
// 数据库连接池只需初始化一次
static {
dataSource = new ComboPooledDataSource("helloc3p0");
}
public static Connection getConnection() throws Exception {
return dataSource.getConnection();
}
/**
* 准备mysql-connector jar和c3p0 jar包
* 1.创建c3p0-config.xml 文件
* 2.创建ComboPooledDataSource实例
* DataSource dataSource =
new ComboPooledDataSource("helloc3p0");
3.从DataSource实例中获取数据库连接。
* @throws Exception
*/
@Test
public void testC3p0WithConfigFile() throws Exception{
DataSource dataSource =
new ComboPooledDataSource("helloc3p0");
System.out.println(dataSource.getConnection());
}
@Test
public void testC3P0() throws Exception{
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver");
cpds.setJdbcUrl("jdbc:mysql:///jdbc");
cpds.setUser("root");
cpds.setPassword("mysql");
System.out.println(cpds.getConnection());
}
}
c3p0配置文件:
<c3p0-config>
<named-config name="helloc3p0">
<!-- 指定连接数据源的基本属性 -->
<property name="user">root</property>
<property name="password">mysql</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///jdbc</property>
<!-- 若数据库中连接数不足时,一次向数据库服务器申请多少个连接 -->
<property name="acquireIncrement">5</property>
<!-- 初始化数据库连接池时连接的数量 -->
<property name="initialPoolSize">5</property>
<!-- 数据库连接池中的最小的数据库连接数 -->
<property name="minPoolSize">5</property>
<!-- 数据库连接池中的最大的数据库连接数 -->
<property name="maxPoolSize">10</property>
<!-- C3P0数据库连接池可以维护的Statement的个数 -->
<property name="maxStatements">20</property>
<!-- 每个连接同时可以使用的Statement 对象的个数 -->
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>