【JDBC】使用连接池重写工具类
<ol><li>
- 连接池原理:
理解为存放多个连接的集合。
目的:解决建立数据库连接耗费资源和时间很多的问题,提高性能。
-
- 常见连接池
Java 为数据库连接池提供了公共的接口:javax.sql.DataSource,各个厂商需要让自己的连接池实现这个接口。这样应用程序可以方便的切换不同厂商的连接池!
连接池名称 | 描述 |
Druid | Druid 是 Java 语言中最好的数据库连接池。Druid 能够提供强大的监控和扩展功能。 |
DBCP | java 数据库连接池的一种,由 Apache 开发,通过数据库连接池,可以让程序自动管理数据库连接的释放和断开。 |
C3P0 | 一个开源的 JDBC 连接池,目前使用它的开源项目有 Hibernate,Spring 等。 |
-
- Druid连接池概述
Druid(德鲁伊)连接池是一个由 alibaba 开发的开源项目,源码托管在 github 上,如果需要下载 jar 包,需要从 maven 的中央仓库中下。
github 地址:https://github.com/alibaba/druid/
maven 仓库地址:http://www.mvnrepository.com/artifact/com.alibaba/druid
-
- Druid 使用
使用 Druid 连接池优化工具类 DruidUtil, 工具类提供两个方法:
获取连接
public static Connection getConn ()
关闭资源
public static void closeResource(ResultSet rs, PreparedStatement pst, Connection conn)
-
-
- 添加 jar 包
-
-
-
- 在 src 表创建 properties 文件
-
文件的内容如下:
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/day05pre
username = root
password = root
initialSize = 5
maxActive = 10
minIdle = 3
maxWait = 60000
解释:
驱动的名字:com.mysql.jdbc.Driver
driverClassName = com.mysql.jdbc.Driver
数据库的地址:jdbc:mysql://localhost:3306/day05pre
url = jdbc:mysql://localhost:3306/day05pre
数据库管理账号和密码
username = root
password = root
初始链接数:5
initialSize = 5
最大并行链接数:10
maxActive = 10
最小空闲数 3
minIdle = 3
最大等待时间 (毫秒):
maxWait = 60000
-
-
- 书写 DruidUtil 工具类
-
做三件事:
1. 读取 properties 文件中的数据 创建连接池对象。
2. 创建一个方法返回一个连接对象
3. 创建一个方法关闭各种资源
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class DruidUtil {
/** 定义一个连接池 */
private static DataSource dataSource;
/** 初始化连接池 */
static{
try {
InputStream is =
DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
Properties prop = new Properties();
prop.load(is);
dataSource = DruidDataSourceFactory.createDataSource(prop);
} catch (Exception e) {
e.printStackTrace();
}
}
/** 通过连接池获取连接 */
public static Connection getConnection() throws SQLException{
return dataSource.getConnection();
}
/** 关闭连接,归还资源 */
public static void closeAll(Connection con,PreparedStatement ps,ResultSet rs) throws SQLException{
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(con!=null){
con.close();
}
}
}
-
-
- 使用工具类完成对数据表的查询
-
/*
* 使用 Druid 连接池工具类 完成查询 student 表中所有的数据
*
* */
@Test
public void findAllDruid() throws SQLException{
// 1. 获取链接
Connection conn = DruidUtil.getConnection();
// 2. 书写 SQL 语句 获取发射器
String sql = "select * from student";
PreparedStatement pst = conn.prepareStatement(sql);
// 3. 执行并处理结果集
ResultSet rs = pst.executeQuery();
while(rs.next()){
// 分别获取各个字段的值
int sid = rs.getInt("sid");
int age = rs.getInt("age");
String name = rs.getString("name");
String sex = rs.getString("sex");
// 显示结果
System.out.println("sid="+sid+"name="+name+"age="+age+"sex="+sex);
}
// 4. 关闭资源
DruidUtil.closeAll(conn, pst, rs);
}