C3P0数据库连接池的基本使用

3 篇文章 0 订阅
2 篇文章 0 订阅

今天学习到了c3p0数据库连接池的三种配置方式:
1、通过ComboPooledDataSource对象提供的一系列setter方法配置
2、通过c3p0-config.xml文件进行配置
3、通过c3p0.properties文件进行配置

注:c3p0数据库连接池需要c3p0.jar 和 mchange-commons-java.jar的支持

先介绍第一种最繁琐的方式:setter

package pers.msidolphin.newcase.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {

    private static ComboPooledDataSource c3p0 = null;

    static {
        try {
            c3p0 = new ComboPooledDataSource();
            //通过setter方法配置
            c3p0.setDriverClass("com.mysql.jdbc.Driver");
            c3p0.setJdbcUrl("jdbc:mysql://localhost:3306/jsp?useUnicode=true&characterEncoding=UTF8&useSSL=true");
            c3p0.setUser("root");
            c3p0.setPassword("root");
            c3p0.setInitialPoolSize(30);
            c3p0.setMaxPoolSize(40);
            c3p0.setMinPoolSize(10);
        }catch(Exception ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Connection getConnection() throws SQLException {
        return C3P0Utils.c3p0.getConnection();
    }

    public static void release(Connection connection) {
        try {
            if(connection != null) {
                connection.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        connection = null;
    }

    public static void release(Statement statement) {
        try {
            if(statement != null) {
                statement.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        statement = null;
    }

    public static void release(ResultSet resultSet) {
        try {
            if(resultSet != null) {
                resultSet.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        resultSet = null;
    }
}

在测试方法中直接调用C3P0Utils的getConnection()静态方法即可获得一个链接

@Test
public void testC3P0() {
    // TODO Auto-generated method stub
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        connection = C3P0Utils.getConnection();
        String sql = "select count(*) from customer";
        statement = connection.prepareStatement(sql);
        resultSet = statement.executeQuery();
        if(resultSet.next()) {
            System.out.println(resultSet.getInt(1));
        }
    }catch(Exception ex) {
        throw new RuntimeException(ex);
    }finally {
        DBCPUtils.release(resultSet);
        DBCPUtils.release(statement);
        DBCPUtils.release(connection);
    }
}

第二种:c3p0-config.xml方式
该文件位于classes目录下

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 默认配置 -->
    <!-- ComboPooledDataSource cpds = new ComoPooledDataSource("intergalactoApp"); 创建ComboPooledDataSource对象时可以指定使用哪个配置,如果不指定则使用默认配置 -->
    <default-config>
        <property name="automaticTestTable">con_test</property>
        <property name="checkoutTimeout">30000</property>
        <property name="idleConnectionTestPeriod">30</property>
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
        <property name="maxStatements">200</property>

        <user-overrides user="test-user">
            <property name="maxPoolSize">10</property>
            <property name="minPoolSize">1</property>
            <property name="maxStatements">0</property>
        </user-overrides>

    </default-config>

    <!-- This app is massive! -->
    <named-config name="mysql">
        <!-- 配置数据库驱动 -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <!-- 配置数据库链接地址 -->
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jsp?useUnicode=true&amp;characterEncoding=UTF8&amp;useSSL=true</property>
        <!-- 配置数据库用户名 -->
        <property name="user">root</property>
        <!-- 配置数据库密码 default: null -->
        <property name="password">root</property>
        <!-- 连接池在无空闲连接可用时一次性创建的新数据库连接数,default: 3 -->
        <property name="acquireIncrement">10</property>
        <!-- 初始化连接数 -->
        <property name="initialPoolSize">30</property>
        <!-- 最小连接数 -->
        <property name="minPoolSize">5</property>
        <!--连接池中保留的最大连接数,default: 15 -->
        <property name="maxPoolSize">40</property>


        <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭,default:0 -->
        <property name="maxStatements">0</property>
        <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数,default: 0 -->
        <property name="maxStatementsPerConnection">5</property>
        <!--c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能 通过多线程实现多个操作同时被执行, default:3 -->
        <property name="numHelperThreads">3</property>
        <!--用户修改系统配置参数执行前最多等待300秒, default: 300 -->
        <property name="propertyCycle">3</property>
        <!-- 获取连接超时设置 默认是一直等待单位毫秒 -->
        <property name="checkoutTimeout">1000</property>
        <!--每多少秒检查所有连接池中的空闲连接, default: 0 -->
        <property name="idleConnectionTestPeriod">3</property>
        <!--最大空闲时间,多少秒内未使用则连接被丢弃。若为0则永不丢弃, default: 0 -->
        <property name="maxIdleTime">10</property>
        <!--配置连接的生存时间,超过这个时间的连接将由连接池自动断开丢弃掉。当然正在使用的连接不会马上断开,而是等待它close再断开。配置为0的时候则不会对连接的生存时间进行限制。 -->
        <property name="maxIdleTimeExcessConnections">5</property>
        <!--两次连接中间隔时间,单位毫秒, default: 1000 -->
        <property name="acquireRetryDelay">1000</property>
        <!--c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试使用, Default: null -->
        <property name="automaticTestTable">Test</property>
        <!-- 获取connnection时测试是否有效 -->
        <property name="testConnectionOnCheckin">true</property>
        <!-- he's important, but there's only one of him -->
        <!--
        <user-overrides user="master-of-the-universe">
            <property name="acquireIncrement">1</property>
            <property name="initialPoolSize">1</property>
            <property name="minPoolSize">1</property>
            <property name="maxPoolSize">5</property>
            <property name="maxStatementsPerConnection">50</property>
        </user-overrides>
          -->
    </named-config>
</c3p0-config>

配置完成后只需要把原来的C3P0Utils工具类的静态代码块稍加修改即可
可以发现并没有显式的指定c3p0去读取c3p0-config.xml文件,因为c3p0会自动在classes目录下查找该文件,所以千万不能更改此文件名

private static ComboPooledDataSource c3p0 = null;

    static {
        try {
            //这个"mysql"就是c3p0-config.xml文件中<named-config>元素配置的name属性值
            c3p0 = new ComboPooledDataSource("mysql");
        }catch(Exception ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

第三种:使用c3p0.properties文件进行配置
该文件同样位于classes目录下
注:属性必须加上c3p0前缀,并且命名要和setter方法一致,采用驼峰法命名

#一些基本配置
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/jsp?useUnicode=true&characterEncoding=UTF8&useSSL=true
c3p0.user=root
c3p0.password=
##[注意] 整数值不能有空格

#初始化时获取10个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 
c3p0.initialPoolSize=10

#当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3
c3p0.acquireIncrement=3
c3p0.maxPoolSize=30
#maxStatements=100
c3p0.minPoolSize=5

#最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0
#maxIdleTime应该小于MySQL的wait_timeout的值
c3p0.maxIdleTime=600

#定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 
c3p0.acquireRetryAttempts=5

#两次连接中间隔时间,单位毫秒。Default: 1000 
c3p0.acquireRetryDelay=1000

#连接关闭时默认将所有未提交的操作回滚。Default: false 
c3p0.autoCommitOnClose=false

#c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么 
#属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试 
#使用。Default: null
#c3p0.automaticTestTable=

#获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 
#保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 
#获取连接失败后该数据源将申明已断开并永久关闭。Default: false
#c3p0.breakAfterAcquireFailure=false

#当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出 
#SQLException,如设为0则无限期等待。单位毫秒。Default: 0
c3p0.checkoutTimeout=10000

#每60秒检查所有连接池中的空闲连接。Default: 0
c3p0.idleConnectionTestPeriod=600

#JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 
#属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 
#如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
c3p0.maxStatements=100

#maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0
c3p0.maxStatementsPerConnection=0

#c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能 
#通过多线程实现多个操作同时被执行。Default: 3
c3p0.numHelperThreads=3

#通过实现ConnectionTester或QueryConnectionTester的类来测试连接。类名需制定全路径。 
#Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester
#c3p0.connectionTesterClassName=

#指定c3p0 libraries的路径,如果(通常都是这样)在本地即可获得那么无需设置,默认null即可 
#Default: null
#c3p0.factoryClassLocation=

#当用户调用getConnection()时使root用户成为去获取连接的用户。主要用于连接池连接非c3p0 
#的数据源时。Default: nul
#c3p0.overrideDefaultUser=root

#与overrideDefaultUser参数对应使用的一个参数。Default: null
#c3p0.overrideDefaultPassword=

#定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意: 
#测试的表必须在初始数据源的时候就存在。Default: null
#c3p0.preferredTestQuery=

#因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 
#时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 
#等方法来提升连接测试的性能。Default: false 
#c3p0.testConnectionOnCheckout=false

#如果设为true那么在取得连接的同时将校验连接的有效性。Default: false 
#c3p0.testConnectionOnCheckin=false

修改C3P0Utils工具类:

private static ComboPooledDataSource c3p0 = null;

    static {
        try {
            c3p0 = new ComboPooledDataSource();
        }catch(Exception ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值