JDBC连接池C3P0

介绍

  C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate,Spring等

XML文件配置

  配置文件名称:c3p0-config.xml(固定)
  配置文件位置:src下(类路径)
  配置文件内容:命名配置

  c3p0-config.xml示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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/java</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="zidingyimingcheng">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/java</property>
<property name="user">root</property>
<property name="password">root</property>
</named-config>


</c3p0-config>

comboPooledDataSource对象读取配置文件

  1. 获取comboPooledDataSource对象
    ComboPooledDataSource combo = new ComboPooledDataSource();   
    或者 ComboPooledDataSource combo = new ComboPooledDataSource(“zidingyimingcheng”);
  2. 获取连接
    Connection conn = combo.getConnection();
  3. 编写SQL
    String sql = “select * from user where id=?”;
  4. 获取到执行sql的对象
    PreparedStatement prep = conn.prepareStatement(sql);
  5. 为sql语句添加参数
    prep.setInt(1, 1);
  6. 执行sql语句
    ResultSet re = prep.executeQuery();

简单代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.rexyan.c3p0;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Test {
@Test
public void JDBC_POOL_C3P0(){
try {
//加载c3p0-config.xml配置文件,实例化可以加名称,不加名称则加载默认配置
ComboPooledDataSource combo = new ComboPooledDataSource("zidingyimingcheng");
//根据配置文件的信息,连接数据库
Connection conn = combo.getConnection();
//书写sql语句
String sql = "select * from user where id=?";
//获取到执行sql的对象
PreparedStatement prep = conn.prepareStatement(sql);
//为sql语句添加参数
prep.setInt(1, 1);
//执行sql语句
ResultSet re = prep.executeQuery();
System.out.println(re.next());

} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

进行封装