c3p0数句库连接池的使用

    xiaoxiao2025-09-04  399

    注:c3p0的使用需要导jar包—c3p0-0.9.1.2.jar

    public class C3p0Demo { @Test public void c3p0Demo() throws PropertyVetoException, SQLException{ ComboPooledDataSource pool = new ComboPooledDataSource(); pool.setUser("root"); pool.setPassword("1234"); pool.setDriverClass("com.mysql.jdbc.Driver"); pool.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/aa?characterEncoding=utf8&useSSL=true"); pool.setMaxPoolSize(1000); for(int i=0;i<1000;i++){ Connection con = pool.getConnection(); System.out.println(i+":"+con); } } @Test//这种方式是通过配置文件方式载入,配置文件放在src根目录下(classpath目录) public void c3p0PropertyDemo() throws SQLException{ ComboPooledDataSource pool = new ComboPooledDataSource("hncu"); pool.setMaxPoolSize(1000); for(int i=0;i<1000;i++){ Connection con = pool.getConnection(); System.out.println(i+":"+con); } } }

    c3p0-config.xml文件内容

    <c3p0-config> <!-- 默认配置,如果没有指定则使用这个配置 --> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl"> <![CDATA[jdbc:mysql://127.0.0.1:3306/mydata?useUnicode=true&characterEncoding=UTF-8&useSSL=true]]> </property> <property name="user">root</property> <property name="password">1234</property> <!-- 初始化池大小 --> <property name="initialPoolSize">2</property> <!-- 最大空闲时间 --> <property name="maxIdleTime">30</property> <!-- 最多有多少个连接 --> <property name="maxPoolSize">10</property> <!-- 最少几个连接 --> <property name="minPoolSize">2</property> <!-- 每次最多可以执行多少个批处理语句 --> <property name="maxStatements">50</property> </default-config> <!-- 命名的配置 --> <named-config name="hncu"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/aa</property> <property name="user">root</property> <property name="password">1234</property> <property name="acquireIncrement">5</property><!-- 如果池中数据连接不够时一次增长多少个 --> <property name="initialPoolSize">100</property> <property name="minPoolSize">50</property> <property name="maxPoolSize">1000</property> <property name="maxStatements">0</property> <property name="maxStatementsPerConnection">5</property> <!-- he's important, but there's only one of him --> </named-config> </c3p0-config>

    自定义c3p0池:

    public class C3p0Pool { private static DataSource pool = null; private static ThreadLocal<Connection> t = new ThreadLocal<Connection>(); static{ pool = new ComboPooledDataSource(); } public static DataSource getDataSource(){ return pool; } public static Connection getConnection() throws SQLException{ Connection con = t.get(); if(con==null){ con = pool.getConnection(); t.set(con); } return con; } }
    转载请注明原文地址: https://ju.6miu.com/read-1302291.html
    最新回复(0)