JDBC连接池-C3P0连接
c3p0连接池的学习英语好的看英文原版 c3p0 - JDBC3 Connection and Statement Pooling
使用c3p0连接池 三种方法:1.实例化和配置 ComboPooledDataSource 2.使用DataSource工厂类 3建立自己池数据源
c3p0 是开源免费的连接池
1.实例化和配置 ComboPooledDataSource
在src目录下添加c3p0-config.xml文件
文件名内容为:
<?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/bookstore</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config> <named-config name="bookStore">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/bookstore</property>
<property name="user">root</property>
<property name="password">root</property>
</named-config> </c3p0-config>
Testc3p0.java
package com.study.jdbc.test; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException; import org.junit.Test; import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.study.jdbc.Utils.C3P0Utils;
import com.study.jdbc.Utils.JDBCUtils_V3; public class TestC3p0 {
@Test
public void test1(){
Connection conn=null;
PreparedStatement pstm=null;
//加载c3p0-config.xml文件中默认的config
ComboPooledDataSource dataSource =new ComboPooledDataSource();
//加载文件中 <named-config name="bookStore"> </named=config> 的配置信息
ComboPooledDataSource dataSource1 =new ComboPooledDataSource("bookStore"); try {
conn=dataSource.getConnection();
System.out.println(conn);
String sql="insert into user values(18,?,?)";
pstm=conn.prepareStatement(sql);
pstm.setString(1,"吕布");
pstm.setString(2,"点错");
int rows =pstm.executeUpdate();
if (rows>0) {
System.out.println("ok");
}else {
System.out.println("no");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
//dataSource.backConnection(conn);
JDBCUtils_V3.release(conn,pstm,null);
} }
}