拓展知识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&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&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>
编写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);
}
}
}
评论区