关于c3p0两种配置
一种是通过set方法进行配置
一种是通过在同src目录下的c3p0-conflg.xml文件或者c3p0.properties文件进行相关的配置。
在Maven依赖中加入c3p0和mysql-connector-java依赖
第一种
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
/**
* 配置DataSource
*/
public static void configDataSource(){
try {
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/xxx");
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setInitialPoolSize(3);
dataSource.setMaxPoolSize(10);
dataSource.setMinPoolSize(3);
dataSource.setAcquireIncrement(3);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
/**
* 获取Connection连接
* @return
*/
public static Connection getConnection(){
Connection conn = null;
configDataSource();
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
第二种(常用)
c3p0通过c3p0-config.xml文件进行配置
这边需要把xml文件方法同src文件夹下的resources目录下
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 默认配置,如果没有指定则使用这个配置 -->
<default-config>
<property name="root">zhanghanlun</property>
<property name="root">123456</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/xxx</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="test">
<property name="user">xxx</property>
<property name="password">xxx</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/xxx</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>
//加载名字为“test”的配置文件
private static ComboPooledDataSource dataSource = new ComboPooledDataSource("test");
/**
* 获取Connection连接
* @return
*/
public static Connection getConnection(){
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}