c3p0数据库连接池

1.下载地址:https://sourceforge.net/projects/c3p0/

2.使用

1)将下载后解压文件内的这两个文件丢进去(可以自行选择版本)

注:这里的mysql-connector的jar包记得要放上去

 

 

 2)代码:

①创建配置文件c3p0-config.xml(我放到src里头)

 

 

<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/javadb</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">10</property>
        <property name="checkoutTimeout">3000</property>

    </default-config>

    <!-- This app is massive! -->
    <named-config name="otherc3p0">
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/javadb</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">8</property>
        <property name="checkoutTimeout">1000</property>
    </named-config>
</c3p0-config>

②运行代码

package util;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class C3P0Demo {
    public static void main(String[] args) throws SQLException {
        //创建数据库连接池对象(没传参数,使用默认配置)
        //DataSource ds = new ComboPooledDataSource();
        //使用指定名称的链接
        DataSource ds = new ComboPooledDataSource("otherc3p0");
        //连接对象
        for(int i = 1; i <= 11; i ++){
            Connection conn = ds.getConnection();
            System.out.println(i + ":" + conn);
            if(i == 5){
                conn.close();
            }
        }

    }
}

 

结果:(这个是执行默认的链接产生的-最大线程池默认10,我执行了11次,等于5的时候释放不报错)

 

 

参阅:https://www.bilibili.com/video/BV1vk4y117fU?p=516

 

posted @ 2022-04-05 22:33  蜗牛的礼物  阅读(71)  评论(0编辑  收藏  举报