c3p0-config.xml
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/blogs?serverTimezone=UTC</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">3</property>
<property name="initialPoolSize">2</property>
<property name="minPoolSize">2</property>
<property name="maxPoolSize">20</property>
</default-config>
</c3p0-config>
C3P0会自动搜索src/.../ c3p0-config.xml,自动配置。
C3p0Utils.java用来负责生产数据库连接
package com.example.sql;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
/*
* 通过c3p0jar包封装一个工具类,c3p0中有一个连接池类,通过创建连接池来获取到一个dateSource对象,通过调用这个
* 对象的getConnection方法获取一个connection连接对象,这就是这个工具类的作用
*
* 对c3p0的理解 ,就是通过c3p0-config.xml配置文件,管理对数据库的连接,实现随时取用,提高效率
*
*/
public class C3p0Utils {
//C3P0连接池提供的核心类: 数据源(就是一个名词,作用是可以调用他的方法给我们一个连接对象)
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
/**
* 配置DataSource,这里是代码配置,也可以xml配置,这里采用xml配置
*/
// public static void configDataSource(){
// try {
// dataSource.setDriverClass("com.mysql.jdbc.Driver");
// dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/zhanghanlun");
// dataSource.setUser("zhanghanlun");
// dataSource.setPassword("123456");
// dataSource.setInitialPoolSize(3);
// dataSource.setMaxPoolSize(10);
// dataSource.setMinPoolSize(3);
// dataSource.setAcquireIncrement(3);
// } catch (PropertyVetoException e) {
// e.printStackTrace();
// }
// }
//获取数据源
public static ComboPooledDataSource getDataSoruce() {
return dataSource;
}
//从连接池中取用一个连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static void releaseConnection(Connection connection){
try {
if(connection != null ) {
connection.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
例子:
public static Map<String,Object> getUserInfo(String id) throws SQLException {
QueryRunner qr = new QueryRunner(C3p0Utils.getDataSoruce());
String sql = "select * from test_login where id = ?";
return qr.query(sql, new MapHandler(), id);
}