概念
本质是一个容器(集合),存放着数据库连接的容器。当系统初始化后,容器被创建,容器中会申请一些连接对象,当用户访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。可以节约资源,使用户高效访问。
标准接口:DataSource(javax.sql包下)这里是引用
方法:获取连接 getConnection() 归还连接Connection.close()。如果连接对象Connection是从连接池中获取的,那么调用Connection.close()方法时不会关闭连接,而是归还连接。
目前主流的数据库连接池 HikariCP C3P0 BoneCP Druid
实现
C3P0
1.导入jar包 下载jar包
2.导入配置文件
将配置文件 C3P0.properties C3P0-config.xml放在src目录下(ps:记得导入数据库驱动jar包)
<default-config>
<!-- 连接参数-->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db1</property>
<property name="user">root</property>
<property name="password">root/property>
<!-- 连接池参数-->
<!-- 初始化申请的连接数量-->
<property name="initialPoolSize">5</property>
<!-- 最大连接数-->
<property name="maxPoolSize">10</property>
<!-- 超时时间-->
<property name="checkoutTimeout">3000</property>
</default-config>
3.创建数据库连接对象 ComboPooledDataSource
DataSource ds=new ComboPooledDataSource();//参数配置名称,空参使用默认配置
4.获取连接:getConnection
Connection connn=ds.getConnection();
Druid
由阿里巴巴开发的数据库连接池技术
1.导入jar包 下载jar包
2.定义配置文件(手动加载,可以放在任意目录下)
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db1
username=root
initialSize=5
maxActive=10
maxWait=3000
3.加载配置文件
//加载配置文件
Properties properties = new Properties();
InputStream is = CruidDemo01.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
4.获取数据库连接池对象:通过工厂来获取DruidDataSourceFactory
//获取连接池对象
DataSource ds = DruidDataSourceFactory.createDataSource(properties);
5.获取连接
Connection connection = ds.getConnection();
JDBC工具类
public class JDBCUtils {
//1.定义成员变量 DataSource
private static DataSource ds;
static {
try {
//2.加载配置文件
Properties properties = new Properties();
properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//3.获取DataSource
ds= DruidDataSourceFactory.createDataSource(properties);
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
/*
* 获取连接
* */
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/*
* 释放资源
* */
public static void close(Statement statement, Connection connection){
close(null,statement,connection);
}
public static void close(ResultSet resultSet,Statement statement, Connection connection){
if (resultSet!=null);{
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!=null);{
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/*
* 获取连接池方法
* */
public static DataSource getDataSource(){
return ds;
}
}