概述
C3P0是一个开源的JDBC连接池,目前使用它的开源项目有Hibernate,Spring等。需要:c3p0-0.9.1.2.jar。
使用配置文件使用
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- default-config 默认的配置, -->
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost/jdbc-study</property>
<property name="user">root</property>
<property name="password">root</property>
<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>
<!-- This app is massive! -->
<named-config name="oracle">
<property name="acquireIncrement">50</property>
<property name="initialPoolSize">100</property>
<property name="minPoolSize">50</property>
<property name="maxPoolSize">1000</property>
<!-- intergalactoApp adopts a different approach to configuring statement caching -->
<property name="maxStatements">0</property>
<property name="maxStatementsPerConnection">5</property>
<!-- he's important, but there's only one of him -->
<user-overrides user="master-of-the-universe">
<property name="acquireIncrement">1</property>
<property name="initialPoolSize">1</property>
<property name="minPoolSize">1</property>
<property name="maxPoolSize">5</property>
<property name="maxStatementsPerConnection">50</property>
</user-overrides>
</named-config>
</c3p0-config>
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class Test {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
//1、构建数据源
ComboPooledDataSource cpds = new ComboPooledDataSource();
//2、得到连接对象
connection = cpds.getConnection();
//3、执行sql语句
String sql = "select * from students";
ps = connection.prepareStatement(sql);
//4、获得结果、处理结果
ResultSet query = ps.executeQuery();
while(query.next()) {
String id = query.getString("id");
String name = query.getString("name");
String clazz = query.getString("clazz");
System.out.println(id + " " + name + " " + clazz);
}
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}