目录
一、添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
二、c3p0-config.xml文件
<c3p0-config>
<named-config name="mysqlapp">
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://192.168.180.141:3306/jdbcstudb</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- 进行数据库连接池管理的基本信息 -->
<!-- 当数据库连接池中的连接数不够时,c3p0一次性向数据库服务器申请的连接数 -->
<property name="acquireIncrement">5</property>
<!-- c3p0数据库连接池中初始化时的连接数 -->
<property name="initialPoolSize">10</property>
<!-- c3p0数据库连接池维护的最少连接数 -->
<property name="minPoolSize">10</property>
<!-- c3p0数据库连接池维护的最多的连接数 -->
<property name="maxPoolSize">600</property>
<!-- c3p0数据库连接池最多维护的Statement的个数 -->
<property name="maxStatements">50</property>
<!-- 每个连接中可以最多使用的Statement的个数 -->
<property name="maxStatementsPerConnection">2</property>
</named-config>
</c3p0-config>
三、编写c3p0工具类
package com.atguigu.kb21.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.atguigu.kb21.dao2.BaseDao2;
import com.atguigu.kb21.pojo.Dog;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* C3P0连接池
*/
public class C3p0Util {
private static DataSource dataSource = null;
static {
dataSource = new ComboPooledDataSource("mysqlapp");
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
BaseDao2<Dog> dao = new BaseDao2<>();
for (int i = 0; i < 1000; i++) {
// mysql同时提供500个连接,如果不关闭,就不能再连接
Connection connection = getConnection();// 批量
// Connection connection = dao.getConnection();// 单次
System.out.println(connection+"连接成功!"+i+"次");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
四、测试运行
五、BaseDao2测试连接功能
public Connection getConnection(){
/*Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;*/
return C3p0Util.getConnection();
}
public static void main(String[] args) {
BaseDao baseDao = new BaseDao();
Connection connection = baseDao.getConnection();
System.out.println(connection+"连接成功");
System.out.println("over");
}