侧边栏壁纸
博主头像
Epoch

Java开发、Python爬虫、微服务、分布式、前端

  • 累计撰写 93 篇文章
  • 累计创建 110 个标签
  • 累计收到 8 条评论

目 录CONTENT

文章目录

拓展知识C3P0连接池

Epoch
2021-02-05 / 0 评论 / 0 点赞 / 315 阅读 / 383 字 / 正在检测是否收录...

拓展知识C3P0连接池

编写我们的c3p0-config.xml

必须是这个命名,约定俗成的

<?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://localhost:3306/bystart?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai&amp;allowPublicKeyRetrieval=true</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <!--连接池初始连接数量-->
        <property name="initialPoolSize">10</property>
        <!--最大连接数量-->
        <property name="maxPoolSize">20</property>
    </default-config>
</c3p0-config>

image-20210205190013926.png

编写demo

package com.xmaven;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.xmaven.utils.DbUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ClassName C3P0Sample
 * @Description TODO
 * @Author Ambition
 * @Date 2021/2/5 18:39
 * @Version 1.0.0
 **/
public class C3P0Sample {

    public static void main(String[] args) {
        //1.加载配置文件  会自动加载我们编写的c3p0-config.xml ,名字必须是这个才能自动加载 所以两步直接合成一步写
        //2.创建DataSourse
        DataSource dataSource = new ComboPooledDataSource();
        //3.得到数据库连接
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            pstmt = conn.prepareStatement("select  * from user limit 0,10");
            rs = pstmt.executeQuery();
            while (rs.next()){
                Integer id = rs.getInt(1);
                String username = rs.getString("username");
                String password = rs.getString("password");
                Float salary = rs.getFloat("salary");
                String dname = rs.getString("dname");
                System.out.println(id + "-" + username + "-" + password + "-" + salary + "-" + dname);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DbUtils.closeConnection(rs,pstmt,conn);
        }

    }

}
0

评论区