标签:
import java.beans.PropertyVetoException; import java.sql.Connection; import org.junit.Test; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * jdbc使用c3p0连接池 * @author APPle * */ public class TestC3P0 { private static String url = "jdbc:mysql://localhost:3306/day19"; private static String user = "root"; private static String password = "root"; private static String driverClass = "com.mysql.jdbc.Driver"; @Test public void test1(){ try { //1.创建连接池对象 ComboPooledDataSource pool = new ComboPooledDataSource(); //2.设置连接参数 pool.setJdbcUrl(url); pool.setUser(user); pool.setDriverClass(driverClass); pool.setPassword(password); //3.设置连接池参数 pool.setInitialPoolSize(5);//初始化连接数 pool.setMaxPoolSize(8);//最大连接数 pool.setCheckoutTimeout(5000);//最大等待时间 //4.获取连接 for(int i=1;i<=9;i++){ Connection conn = pool.getConnection(); //遵守sun公司的jdbc的DataSource接口规范:所有连接池对象必须实现的接口 System.out.println(conn); if(i==3){ //返回池中 conn.close(); } } } catch (Exception e) { e.printStackTrace(); } } /** * 使用配置文件设置连接参数和连接池参数 * 默认规则:c3p0启动时会到当前项目的类路径下,读取一个叫c3p0-config.xml文件。 */ @Test public void test2(){ try { //1.创建连接池对象 //连接一个数据库只能创建一个连接池对象 //ComboPooledDataSource pool = new ComboPooledDataSource();//对应的是使用default-config的参数去创建连接池 ComboPooledDataSource pool = new ComboPooledDataSource("oracle");//对应的使用名称为oracle的name-config的参数去创建连接池 //2.获取连接 for(int i=1;i<=9;i++){ Connection conn = pool.getConnection(); //遵守sun公司的jdbc的DataSource接口规范:所有连接池对象必须实现的接口 System.out.println(conn); if(i==3){ //返回池中 conn.close(); } } } catch (Exception e) { e.printStackTrace(); } } }
<c3p0-config> <!-- 默认配置 --> <default-config> <property name="jdbcUrl">jdbc:mysql://localhost:3306/day19</property> <property name="user">root</property> <property name="password">root</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">8</property> <property name="checkoutTimeout">5000</property> </default-config> <!-- 命名配置 --> <named-config name="oracle"> <property name="jdbcUrl">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="user">eric</property> <property name="password">123456</property> <property name="driverClass">oracle.jdbc.driver.OracleDriver</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">8</property> <property name="checkoutTimeout">5000</property> </named-config> </c3p0-config>
标签:
原文地址:http://www.cnblogs.com/Coolkaka/p/5939331.html