-----两个依赖
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
方式1—dbcp(要导入这个依赖)
package TestPool;
import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.Connection;
public class TestMysqlDbcp4Pool {
public static void main(String[] args) throws Exception {
//创建连接池
//dbcp:是针对可以使用jdbc连接的数据库
BasicDataSource basicDataSource = new BasicDataSource();
//指定连接信息
basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
basicDataSource.setUrl("jdbc:mysql://master:3306/user");
basicDataSource.setUsername("root");
basicDataSource.setPassword("123456");
//连接池在创建的时候创建几个连接
basicDataSource.setInitialSize(2);
//最大的连接数
basicDataSource.setMaxIdle(10);
//从连接池中获取连接
Connection connection = basicDataSource.getConnection();
//获取活跃的连接池数量
System.out.println(basicDataSource.getNumActive());
//关闭连接,相当于将连接放回连接池
connection.close();
}
}
方式2—c3p0(要导入依赖)
package TestPool;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
public class TestMysqlc3p0Pool {
public static void main(String[] args) throws Exception {
/**
* 创建c3p0连接池
*
*/
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//指定连接信息
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jsbc:mysql://master:3306/user");
dataSource.setUser("root");
dataSource.setPassword("123456");
//连接池在创建的时候创建几个连接
dataSource.setInitialPoolSize(2);
//最大的连接数
dataSource.setMaxPoolSize(10);
//获取连接
Connection connection = dataSource.getConnection();
//关闭连接
connection.close();
}
}