一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

 

一、c3p0

  1、引jar包:c3p0

  2、配置文件

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://172.21.22.5:3306/studymysql</property>
        <property name="user">root</property>
        <property name="password">123456</property>

        <!--初始化连接数-->
        <property name="initialPoolSize">5</property>
        <!--连接超时时间-->
        <property name="checkoutTimeout">30000</property>
        <!--最大连接数-->
        <property name="maxPoolSize">10</property>
    </default-config>

    <named-config name="mySource">
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://172.21.22.5:3306/studymysql</property>
        <property name="user">root</property>
        <property name="password">123456</property>

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

  3、代码

public class PoolApplication {
    public static void main(String[] args) throws SQLException {
/*
1、c3p0连接池默认会读取src目录下的c3p0-config.xml或者c3p0.properties配置文件
2、new ComboPooledDataSource(String):参数不传则读取配置文件中default-config的配置
    传named-config的name属性,则读取该named-config的配置
3、Connection getConnection():获取连接
*/
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("mySource");

        for (int i = 0; i < 10; i++) {
            Connection connection = comboPooledDataSource.getConnection();
            if (i == 0 || i == 1) {
                connection.close();
            }
            System.out.println(connection);
        }
    }
}

 

二、druid

  1、引jar包:druid

  2、配置文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://172.21.22.5:3306/studymysql
username=root
password=123456
initialSize=5
maxActive=10
maxWait=30000

  3、代码

public class DruidApplication {
    public static void main(String[] args) throws Exception {
/*
1、DataSource createDataSource(Properties):获取连接池
2、Connection getConnection():获取连接
*/
        ClassLoader classLoader = DruidApplication.class.getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("druid.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);

        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
}

 

posted on 2020-08-26 09:52  一路繁花似锦绣前程  阅读(117)  评论(0编辑  收藏  举报