package com.ydsc3p0; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import com.mchange.v2.c3p0.DataSources; /** * 另一种创创建链接池 * @author yu * */ public class DbUtils2 { public static void main(String[] args) { //简单的实现方式 simple(); //配置属性 SimpleAttr(); } /** * 简单的实现方式 */ private static void simple(){ try { DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:mysql://localhost:3306/day05?characterEncoding=UTF-8", "root", "1234"); System.out.println(ds_unpooled.getConnection()); } catch (SQLException e) { e.printStackTrace(); } } private static void SimpleAttr() { try { DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:mysql://localhost:3306/day05?characterEncoding=UTF-8", "root", "1234"); //带有属性的创建方式 Map overrides = new HashMap(); overrides.put("maxStatements", "200"); //Stringified property values work overrides.put("maxPoolSize", new Integer(50)); //"boxed primitives" also work DataSource unpooled = DataSources.pooledDataSource(ds_unpooled,overrides); //创建自定义的名称 //DataSource unpooled = DataSources.pooledDataSource(ds_unpooled,"myPool",overrides); System.out.println(ds_unpooled.getConnection()); } catch (SQLException e) { e.printStackTrace(); } } }
常用配置说明
package com.ydsc3p0; import java.beans.PropertyVetoException; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * C3P0的工具类 第一个简单的C3P0类 是否能得到链接 * * @author yu */ public class DbUtil { public static void main(String[] args) { ComboPooledDataSource cpds=getDs(); //设置预处理的数、两者都默认是0 cpds.setMaxStatements(100); //cpds.setMaxStatementsPerConnection(100); //设置最小链接数 cpds.setMinPoolSize(5); //当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 cpds.setAcquireIncrement(3); //设置最大链接数 cpds.setMaxPoolSize(20); //得到链接池的名称 String poolName=cpds.getDataSourceName(); System.out.println(poolName); //关闭 cpds.close(); } public static ComboPooledDataSource getDs() { // 创建链接池 ComboPooledDataSource cpds = new ComboPooledDataSource(); //创建自己链接池名称 //ComboPooledDataSource cpds = new ComboPooledDataSource("myPool"); try { // 设置驱动 cpds.setDriverClass("com.mysql.jdbc.Driver"); // 设置链接地址 cpds.setJdbcUrl("jdbc:mysql://localhost:3306/day05?characterEncoding=UTF-8"); // 设置用户名 cpds.setUser("root"); // 设置密码 cpds.setPassword("1234"); } catch (PropertyVetoException e) { e.printStackTrace(); } return cpds; } }
关闭
DataSources.destroy( ds_pooled );
原文地址:http://ityds.blog.51cto.com/1831752/1812644