介绍
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对象读取配置文件
- 获取comboPooledDataSource对象
ComboPooledDataSource combo = new ComboPooledDataSource();
或者 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();
简单代码示例
1 | package com.rexyan.c3p0; |