使用Druid连接池重写工具类
1,连接池原理:
理解为存放多个连接的集合
目的:解决建立数据库连接耗费资源和时间很多的问题,提高性能。
2,常见连接池
Java为数据库连接池提供了公共的接口:javax.sql.DataSource,各个厂商需要让自己的连接池实现这个接口。这样应用程序可以方便的切换不同厂商的连接池!
3,Druid连接池概述
Druid(德鲁伊)连接池是一个由alibaba开发的开源项目,源码托管在github上,如果需要下载jar包,需要从maven的中央仓库中下。
github地址:https://github.com/alibaba/druid/
maven仓库地址:http://www.mvnrepository.com/artifact/com.alibaba/druid
4,Druid使用
使用Druid连接池优化工具类DruidUtil,工具类提供两个方法:
获取连接
public static Connection getConn ()
关闭资源
public static void closeResource(ResultSet rs, PreparedStatement pst, Connection conn)
4.1添加jar包
4.2添加配置文件
驱动的名字:com.mysql.jdbc.Driver
driverClassName = com.mysql.jdbc.Driver
数据库的地址:jdbc:mysql://localhost:3308/onetwo
url = jdbc:mysql://localhost:3308/onetwo
数据库管理账号和密码
username = root
password = root
初始链接数:5
initialSize = 5
最大并行链接数:10
maxActive = 10
最小空闲数 3
minIdle = 3
最大等待时间(毫秒):
maxWait = 60000
4.3书写DruidUtil工具类
做三件事:
1.读取properties文件中的数据 创建连接池对象。
2.创建一个方法返回一个连接对象
3.创建一个方法关闭各种资源
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();
}
}
}
4.4使用工具类完成对数据表的查询
@Test
public void findAllDruid() throws SQLException {
// 1.获取链接
Connection conn = DruidUtil.getConnection();
// 2.书写SQL语句 获取发射器
String sql = "\n" +
"select * from t_student\n";
PreparedStatement pst = conn.prepareStatement(sql);
// 3.执行并处理结果集
ResultSet rs = pst.executeQuery();
while(rs.next()){
//分别获取各个字段的值
int id = rs.getInt("id");
//显示结果
System.out.println("sid="+id);
}
// 4.关闭资源
DruidUtil.closeAll(conn, pst, rs);
}