C3P0连接池介绍
c3p0的出现,是为了大大提高应用程序和数据库之间访问效率的。
它的特性:
1、编码的简单易用
2、连接的复用
3、连接的管理
## C3P0导入jar包
* a: jar包介绍
* mysql-connector-java-5.1.47-bin.jar:数据库驱动
* commons-dbutils-1.7.jar:提供QueryRunner类方便进行增删改查操作
// 以下两个为c3p0必须的jar包
* c3p0-0.9.5.2.jar
// java.lang.NoClassDefFoundError:com.mchange.v2.ser.Indirector
* mchange-commons-java-0.2.11.jar
- b: 导入jar包
- 在项目根路径下建立文件夹lib
- 拷贝以上jar包,选定拷贝的jar包/右键/Build Path/Add to Build Path
C3P0的参数配置
在src目录下新建一个名叫 c3p0-config.xml 的文件,注意,必须是这个文件名。
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--默认配置-->
<default-config>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!--配置连接池mysql-->
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///j1805?useSSL=false</property>
<property name="user">root</property>
<property name="password">root</property>
<!--初始化时的连接数-->
<property name="initialPoolSize">10</property>
<!--连接池中最大和最小的连接数-->
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<!--连接的最大空闲时间-->
<property name="maxIdleTime">30</property>
<property name="maxStatements">200</property>
</named-config>
<named-cnfig name="otherDB">
</named-config>
</c3p0-config>
c3p0工具类的封装
public class c3p0Utils {
// c3p0如果没有静态代码块设置,默认会自动去项目中找c3po-config.xml文件来加载链接参数
// 因此需要在src下创建一个c3p0-config.xml文件
private static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");
// 如果没有配置xml文件,可以使用静态代码块在项目中直接设置连接参数
// static {
// try {
// dataSource.setDriverClass("com.mysql.jdbc.Driver");
// dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/j1805?useSSL=false");
// dataSource.setUser("root");
// dataSource.setPassword("root");
// } catch (PropertyVetoException e) {
// throw new RuntimeException("链接数据库异常"+e);
// }
// }
// 直接返回连接池数据源对象
public static ComboPooledDataSource getDataSource() {
return dataSource;
}
// 返回数据库链接对象
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("链接数据库异常"+e);
}
}
}