• C3P0数据库连接池


    C3P0数据库连接池

     1.创建c3p0-config.xml文件

     2.创建ComboPooledDataSource实例

    DataSource dataSource = new ComboPooledDataSource("helloc3p0");

     3.从DataSource实例中获取数据库连接。

        @Test
        public void testC3P0WithConfigFile() throws Exception{
            DataSource dataSource = new ComboPooledDataSource("c3p0");
            System.out.println(dataSource.getConnection());
    
            ComboPooledDataSource comboPooledDataSource = (ComboPooledDataSource) dataSource;
            System.out.println(comboPooledDataSource.getMaxStatements());
        }
    

      

    c3p0-config.xml配置文件

    <c3p0-config>
        <name-config name="c3p0">
    
            <!--指定连接数据源的基本属性-->
            <property name="user">root</property>
            <property name="password">password</property>
            <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/yang</property>
    
            <!--若数据库中连接数不足时,一次向数据库服务器申请多少个连接-->
            <property name="acquireIncrement">5</property>
            <!--初始化数据库连接池时连接的数量-->
            <property name="initialPoolSize">5</property>
            <!--数据库连接池中最小的数据库连接数-->
            <property name="minPoolSize">5</property>
            <!--数据库连接池中最大的数据库连接数-->
            <property name="maxPoolSize">10</property>
    
            <!--C3P0数据库连接池可以维护的Statement的个数-->
            <property name="maxStatements">20</property>
            <!--每个连接同时可以使用Statement对象的个数-->
            <property name="maxStatementsPerConnection">5</property>
        </name-config>
    
    </c3p0-config>
    

      封装成的方法

    private static DataSource dataSource = null;
    
        //数据库连接池只被初始化一次
        static {
            dataSource =new  ComboPooledDataSource("helloc3p0");
        }
    
        public static Connection getConnection2() throws Exception{
            return dataSource.getConnection();
        }
    if(conn != null){
    try {
    //数据库连接池的Connection对象进行close时,
    // 并不是真的进行关闭,而是把该数据库连接归还到数据库连接池中。
    conn.close();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

      

  • 相关阅读:
    深入浅出TCP之listen
    indexing and hashing
    c++四种强制类型转化
    c++实现web服务框架
    MVC、MVP、MVVM概念解析
    常用设计模式
    [React]虚拟DOM
    防抖和节流
    函数柯里化
    apply, bind, call方法剖析
  • 原文地址:https://www.cnblogs.com/yangHS/p/10845454.html
Copyright © 2020-2023  润新知