- package cn.itcast.test;
- import java.beans.PropertyVetoException;
- import java.sql.Connection;
- import java.sql.SQLException;
- import org.junit.Test;
- import com.mchange.v2.c3p0.ComboPooledDataSource;
- /**
- * 演示 c3p0 连接池
- * @author 国真
- * 1. 需要两个 jar 包: c3p0-0.9.2-pre1.jar 和 mchange-commons-0.2.jar
- * 2. fun1() 使用代码来创建连接池对象
- * fun2() 使用默认配置,<default-config>
- * fun3() 使用命名配置,<name-config name="mysqlConfig">
- */
- public class Demo {@Test public void fun1() throws PropertyVetoException,
- SQLException {
- // 创建连接池对象
- ComboPooledDataSource ds = new ComboPooledDataSource();
- // 连接参数配置 (四大参数)
- ds.setDriverClass("com.mysql.jdbc.Driver");
- ds.setJdbcUrl("jdbc:mysql://localhost:3306/test");
- ds.setUser("root");
- ds.setPassword("admin");
- // 池配置省略
- // 获取连接
- Connection connection = ds.getConnection();
- System.out.println(connection.getClass().getName()); // 返回 connection 对象所代表的具体对象的名称
- connection.close();
- }@Test public void fun2() throws PropertyVetoException,
- SQLException {
- // 创建连接池对象
- ComboPooledDataSource ds = new ComboPooledDataSource();
- Connection connection = ds.getConnection();
- System.out.println(connection.getClass().getName());
- connection.close();
- // 关闭池连接
- ds.close();
- }@Test public void fun3() throws PropertyVetoException,
- SQLException {
- // 创建连接池对象
- ComboPooledDataSource ds = new ComboPooledDataSource("mysqlConfig"); // 若给出了参数, 则该参数就是 < name-config > 的名称
- Connection connection = ds.getConnection();
- System.out.println(connection.getClass().getName());
- connection.close();
- // 关闭池连接
- ds.close();
- }
- }
- <?xml version="1.0" encoding="UTF-8" ?>
- <c3p0-config>
- <default-config>
- <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
- <property name="driverClass">com.mysql.jdbc.Driver</property>
- <property name="user">root</property>
- <property name="password">admin</property>
- <property name="acquireIncrement">3</property>
- <property name="initialPoolSize">10</property>
- <property name="minPoolSize">2</property>
- <property name="maxPoolSize">10</property>
- </default-config>
- <name-config name="mysqlConfig">
- <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
- <property name="driverClass">com.mysql.jdbc.Driver</property>
- <property name="user">root</property>
- <property name="password">admin</property>
- <property name="acquireIncrement">3</property>
- <property name="initialPoolSize">10</property>
- <property name="minPoolSize">2</property>
- <property name="maxPoolSize">10</property>
- </name-config>
- </c3p0-config>
c3p0 数据库连接池使用
来源: http://www.bubuko.com/infodetail-2490488.html