c3p0-config.xml


c3p0-config.xml

一般将 c3p0 连接池的配置文件放置到到src目录下,该文件制订了连接数据库和连接池的相关参数。可以更方便的连接MySQL数据库。

<?xml version="1.0" encoding="UTF-8"?>


    
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/jdbc
        root
        java

        10
        30
        100
        10
    

    
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/test
        root
        xxx

        10
        30
        100
        10
        5
        2
    

示例代码

无xml配置文件

public void testC3P0_01(){
        //创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        //通过配置文件获取相关的信息
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\mysql.properties"));
            //读取相关的属性值
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String url = properties.getProperty("url");
            String driver = properties.getProperty("driver");
            //给数据源设置相关的参数
            comboPooledDataSource.setDriverClass(driver);//驱动类
            comboPooledDataSource.setJdbcUrl(url);
            comboPooledDataSource.setUser(user);
            comboPooledDataSource.setPassword(password);
            //初始化连接数
            comboPooledDataSource.setInitialPoolSize(10);
            //设置最大连接数
            comboPooledDataSource.setMaxPoolSize(50);

            //测试连接池效率,连接MySQL5000次
            long start = System.currentTimeMillis();
            for (int i = 0; i < 5000; i++) {
                //得到连接
                Connection connection = comboPooledDataSource.getConnection();//这个方法就是从 DataSource 接口实现
//                System.out.println("连接成功!");
                connection.close();//关闭连接
            }
            long end = System.currentTimeMillis();
            System.out.println("用时:"+(end-start));//1800ms左右
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

有xml配置文件

public void testC3P0_02() throws SQLException {
        ComboPooledDataSource mySource = new ComboPooledDataSource("mySource");
    //下面的代码用来计算连接 5000 次数据库所需的时间
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            Connection connection = mySource.getConnection();
//            System.out.println("2连接成功!");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("配置文件连接用时:"+(end-start));//91ms
    }

从上面的代码可以发现,c3p0可以更高效地连接数据库,而且所提供的的配置文件,使得在开发过程中的代码大幅度减少,不愧为一大利器。