JDBC配置C3P0数据库连接池(三种方式)

添加maven依赖


    mysql
    mysql-connector-java
    8.0.15



    com.mchange
    c3p0
    0.9.5.4

一、set属性配置

    public void testC3P0() throws Exception {
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver");
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/jdbc_test?serverTimezone=GMT%2B8");
        cpds.setUser("root");
        cpds.setPassword("root123");

        Connection conn = cpds.getConnection();
        System.out.println(conn);

//        并不是真正的关闭,而是归还给数据库连接池
        conn.close();
    }

二、xml配置

在类路径下新建c3p0-config-xml




    

        
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/jdbc_test?serverTimezone=GMT%2B8
        root
        root123

        
        5
        
        5
        
        5
        
        10

        
        20
        
        5

    

使用:

    public void testC3P0WithXML() throws Exception {
        DataSource dataSource = new ComboPooledDataSource("helloc3p0");

        Connection conn = dataSource.getConnection();
        System.out.println(conn);

        conn.close();
    }

三、properties配置

在类路径下新建c3p0.properties

c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/jdbc_test?serverTimezone=GMT%2B8
c3p0.user=root
c3p0.password=root123

c3p0.acquireIncrement=5
c3p0.initialPoolSize=5
c3p0.minPoolSize=5
c3p0.maxPoolSize=10

c3p0.maxStatements=20
c3p0.maxStatementsPerConnection=5

使用:

    public void testC3P0WithProp() throws Exception {
        DataSource dataSource = new ComboPooledDataSource();
        Connection conn = dataSource.getConnection();
        System.out.println(conn);

        conn.close();
    }

 

你可能感兴趣的:(jdbc)