driver: libs下
c3p0XXXX.jar : libs
c3p0.xml:src下
<c3p0-config>
<!-- 数据源名称代表连接池 -->
<named-config name="hello">
<!-- 驱动类 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- url-->
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/girls</property>
<!-- 用户名 -->
<property name="user">root</property>
<!-- 密码 -->
<property name="password">root</property>
<!-- 每次增长的连接数-->
<property name="acquireIncrement">5</property>
<!-- 初始的连接数 -->
<property name="initialPoolSize">10</property>
<!-- 最小连接数 -->
<property name="minPoolSize">5</property>
<!-- 最大连接数 -->
<property name="maxPoolSize">10</property>
<!-- 可连接的最多的命令对象数 -->
<property name="maxStatements">5</property>
<!-- 每个连接对象可连接的最多的命令对象数 -->
<property name="maxStatementsPerConnection">2</property>
</named-config>
</c3p0-config>
两种连接方式
package com.hspedu.jdbc.myjdbc;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.jupiter.api.Test;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* @ProjectName: JDBC
* @Package: com.hspedu.jdbc.myjdbc
* @ClassName: ConnPool
* @Description: java类作用描述
* @Author:
* @CreateDate: 2021/9/8 9:26
* @UpdateDate: 2021/9/8 9:26
* @Version: 1.0
*/
public class C3P0_ {
@Test
public void testC3P0_01() throws IOException, PropertyVetoException, SQLException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
Properties properties = new Properties();
properties.load(new FileInputStream("mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setPassword(password);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setInitialPoolSize(10);
comboPooledDataSource.setMaxPoolSize(50);
long st = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
Connection connection = comboPooledDataSource.getConnection();
connection.close();
}
long end = System.currentTimeMillis();
System.out.println((end-st));
System.out.println("succ");
}
//第二种方式 使用配置文件模板来完成
// 1. 将 c3p0 提供的 c3p0.config.xml 拷贝到 src 目录下
// 2. 该文件指定了连接数据库和连接池的相关参数
@Test
public void testC3P0_02() throws SQLException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hello"); //测试 5000 次连接 mysql
long start = System.currentTimeMillis();
System.out.println("开始执行....");
for (int i = 0; i < 500000; i++) {
Connection connection = comboPooledDataSource.getConnection();
//System.out.println("连接 OK~");
connection.close();
}
long end = System.currentTimeMillis(); //c3p0 的第二种方式 耗时=413
System.out.println("c3p0 的第二种方式(500000) 耗时=" + (end - start));//1917
//
}
}