C3p0数据库连接池技术

C3p0是使用步骤

1.导入jar包或者maven依赖
①c3p0-0.XX.jar ②mchange-commons-jar.jar ③mysql-connector.jar

或者maven依赖

 <!--测试包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.8</version>
    </dependency>
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

2.src或者resource下直接配置c3p0-config.xml[建议使用它]或者cc3p0.properties文件【使用这个一直出错找不到原因】 【系统自己找路径。文件名有规定。】
3.创建数据库连接对象

ComboPooledDataSource dataSource = new ComboPooledDataSource();

4.获取连接

Connection connection = dataSource.getConnection();

案例

public class Test2 {
@Test
    public void  te(){
        Flower f;
        ArrayList<Flower> flowers = new ArrayList<>();
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            Connection connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from flower");
            while (resultSet.next()){
                flowers.add(new Flower(resultSet.getInt("id"),
                        resultSet.getString("name"),
                        resultSet.getDouble("price")));

            }
            for (Flower fl:flowers
            ) {
                System.out.println(fl.getName());
                System.out.println(fl.getPrice());
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

c3p0-config.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!--使用默认的配置读取连接池对象-->
    <default-config>
        <!--连接参数-->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/demo6</property>
        <property name="user">root</property>
        <property name="password">123456</property>
        <!--连接池参数-->
        <!--初始化申请的连接数量-->
        <property name="initialPoolSize">5</property>
        <!--超时时间-->
        <property name="checkoutTimeout">3000</property>
        <property name="maxIdleTime">30</property>
        <!--最大的连接数量-->
        <property name="maxPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxStatements">200</property>
    </default-config>
</c3p0-config>
上一篇:JDBC高级


下一篇:Mysql学习