数据库连接池之ComboPooledDataSource

数据库的连接池有很多,今天来学习一下ComboPooledDataSource;

需要的jar包:


    c3p0
    c3p0
    0.9.1.2

因为是mysql数据库,所以还需要


    mysql
    mysql-connector-java
    5.1.34

第一种方式:不采用配置文件配置,纯java代码连接:

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;


public class TestCombo{
    private ComboPooledDataSource dataSource;

    private TestCombo() {
        try {
            dataSource = new ComboPooledDataSource();
            dataSource.setUser(root);
            dataSource.setPassword(123456);
            dataSource.setJdbcUrl(jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8");
            dataSource.setDriverClass(com.mysql.jdbc.Driver);
            dataSource.setInitialPoolSize();
            dataSource.setAcquireIncrement();
            dataSource.setMinPoolSize();
            dataSource.setMaxPoolSize();
            dataSource.setMaxStatements();
            dataSource.setMaxIdleTime();
            dataSource.setIdleConnectionTestPeriod();
            dataSource.setAcquireRetryAttempts();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

  
    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (Exception e) {
            throw new RuntimeException("can not get sms database connection  ", e);
        }
    }

}
第二种方式(配置文件)

 

配置文件:c3p0-config.xml 

名字必须为这个!





           

        com.mysql.jdbc.Driver

        

            

        

        root

        1234

        

        2

        

        30

        

        10

        

        2

        

        50

         

    

        com.mysql.jdbc.Driver

        

        root

        1234

        5

        100

        50

        1000

        0

        5

 

    

 

代码中获取实例:

ComboPooledDataSource pool = new ComboPooledDataSource();//空参,自动到classpath目录下面加载“c3p0-config.xml”配置文件---配置文件的存储位置和名称必须是这样,且使用“默认配置”
ComboPooledDataSource pool = new ComboPooledDataSource("demo");//加载“c3p0-config.xml”文件中定义的“demo”这个配置元素


---------------------
作者:chenpuzhen
来源:CSDN
原文:https://blog.csdn.net/chenpuzhen/article/details/80610044

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(数据库)