MySQL---数据库从入门走向大神系列(十四)-ComboPooledDataSource(C3P0连接池配置)


From:http://blog.csdn.net/qq_26525215/article/details/52212260

需要准备的jar包:

MySQL的jar包mysql-connector-Java-5.1.39-bin目前是5.1.39版本:
http://dev.mysql.com/downloads/connector/j/

C3p0的2个包:
https://sourceforge.net/projects/c3p0/
c3p0-0.9.1.2.jar和c3p0-sources-0.9.1.2.jar

配置文件: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/hncu?useUnicode=true&characterEncoding=UTF-8]]>
        </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="demo">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl"><![CDATA[jdbc:mysql://127.0.0.1:3306/hncu?useUnicode=true&characterEncoding=UTF-8]]></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> 

演示代码:

package cn.hncu.C3p0;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import org.junit.Test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3p0Demo {

    @Test
    // 纯Java方法使用c3p0
    public void C3p0Demo() throws PropertyVetoException, SQLException {
        ComboPooledDataSource pool = new ComboPooledDataSource();
        pool.setUser("root");// 用户姓名
        pool.setPassword("1234");// 用户密码
        pool.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/hncu?useUnicode=true&characterEncoding=utf-8");// MySQL数据库连接url
        pool.setDriverClass("com.mysql.jdbc.Driver");

        // pool可以调用set方法进行Connection池的配置

        // 连接关闭之后,内存会被释放,下次取时会重新开(内存地址不共用)
        for (int i = 0; i < 20; i++) {
            Connection con = pool.getConnection();
            System.out.println(i + ":" + con);
            if (i % 2 == 0) {
                con.close();
            }
        }
    }

    @Test
    // 演示采用配置文件的方式使用c3p0
    public void C3p0PropertyDemo() throws SQLException {
        ComboPooledDataSource pool = new ComboPooledDataSource();//空参,自动到classpath目录下面加载“c3p0-config.xml”配置文件---配置文件的存储位置和名称必须是这样,且使用“默认配置”
        //ComboPooledDataSource pool = new ComboPooledDataSource("demo");//加载“c3p0-config.xml”文件中定义的“demo”这个配置元素
         for(int i=0;i<25;i++){
               Connection con = pool.getConnection();
               System.out.println(i+":"+ con.hashCode());
           }
    }

}

包装一下C3P0的Connection池

package cn.hncu.C3p0;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3p0Pool {
    //我们的这个包装,只是为了把c3p0池做成让每个线程(客户端)获得的是同一个连接,方便做b/s框架下的事务
    private static DataSource pool;
    private static ThreadLocal<Connection> t = new ThreadLocal<Connection>();
    static{
        pool = new ComboPooledDataSource("demo");
        //这里的参数视你的配置文件而定,也可以不写,用默认的配置
    }

    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;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,需要在项目中导入c3p0相关的jar包,可以在maven中添加以下依赖: ```xml <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> ``` 然后,在项目中创建一个c3p0配置文件,例如命名为c3p0-config.xml,内容如下: ```xml <?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <!--初始化连接池时,连接池中连接的个数--> <initialPoolSize>3</initialPoolSize> <!--连接池最多保存的连接数--> <maxPoolSize>10</maxPoolSize> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数--> <acquireIncrement>3</acquireIncrement> <!--连接超时时间--> <checkoutTimeout>60000</checkoutTimeout> <!--当连接池中连接空闲时间大于idleConnectionTestPeriod所指定的时间时,c3p0则会测试连接池中的连接有效性。--> <idleConnectionTestPeriod>60</idleConnectionTestPeriod> <!--如果设为true那么在取得连接的同时将校验连接的有效性。建议使用idleConnectionTestPeriod或automaticTestTable等方法来提升连接测试的可靠性。--> <testConnectionOnCheckin>false</testConnectionOnCheckin> <!--如果设为true那么在归还连接的同时将校验连接的有效性。建议使用idleConnectionTestPeriod或automaticTestTable等方法来提升连接测试的可靠性。--> <testConnectionOnCheckout>false</testConnectionOnCheckout> <!--自动提交--> <autoCommitOnClose>true</autoCommitOnClose> <!--打印连接详细信息--> <debug>true</debug> <!--MySQL数据库的驱动程序--> <driverClass>com.mysql.jdbc.Driver</driverClass> <!--连接的URL--> <jdbcUrl>jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false</jdbcUrl> <!--用户名--> <user>root</user> <!--密码--> <password>123456</password> <!--定义了一个标准的数据库查询语句,用来测试连接池中连接的可用性,如果执行失败,则抛出SQLException异常,表示该连接已经不可用了。--> <preferredTestQuery>select 1</preferredTestQuery> </c3p0-config> ``` 其中,需要根据实际情况修改jdbcUrl、user和password等参数。 最后,在Java代码中使用c3p0连接池,示例代码如下: ```java public class DBUtil { //定义一个C3P0数据源 private static ComboPooledDataSource ds = new ComboPooledDataSource("mysql"); /** * 获取连接对象 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } /** * 关闭连接对象、Statement对象和ResultSet对象 */ public static void close(Connection conn, Statement stmt, ResultSet rs) { try { if(rs != null) { rs.close(); } if(stmt != null) { stmt.close(); } if(conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } ``` 在具体使用时,可以通过DBUtil.getConnection()方法获取连接对象,并通过DBUtil.close()方法关闭连接对象、Statement对象和ResultSet对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值