阿里巴巴Druid连接池的配置与使用
配置文件:
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/imooc?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username=root
password=root
initialSize=10
maxActive=20
使用:
/**
* Druid连接池配置与使用
*/
public class DruidSample {
public static void main(String[] args) {
//1. 加载属性文件
Properties properties = new Properties();
String propertyFile = DruidSample.class.getResource("/druid-config.properties").getPath();
//空格->%20 | c:\java code\druid-config.properties
//c:\java%20code\druid-config.properties
try {
propertyFile = new URLDecoder().decode(propertyFile, "UTF-8");
properties.load(new FileInputStream(propertyFile));
} catch (Exception e) {
e.printStackTrace();
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
//2. 获取DataSource数据源对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
//3. 创建数据库连接
conn = dataSource.getConnection();
pstmt = conn.prepareStatement("select * from employee limit 0,10");
rs = pstmt.executeQuery();
while (rs.next()) {
Integer empId = rs.getInt(1);
String ename = rs.getString("ename");
String dname = rs.getString("dname");
Float salary = rs.getFloat("salary");
System.out.println(dname + "-" + empId + "-" + ename + "-" + salary);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
/**
* 不使用连接池:conn.close()关闭连接
* 使用连接池:conn.close()将连接回收至连接池
*/
DbUtils.closeConnection(rs,pstmt,conn);
}
}
}
其实,连接池不是什么很高深的概念。web服务器和数据库服务器之间的通信也要经过套接字。如果每次操作数据库时都要新建tcp连接太费时间,而且还要经过数据库用户和权限认证的过程。不如先把连接建好,并为数据库服务器端的套接字创建负责读写它的线程。这样,如果web服务器的某个线程需要和数据库服务器通信,直接向web服务端的一个已建好连接的套接字写东西或读东西就行了,数据库那端的线程会负责处理的。
另外,DataSource类的官方描述是物理数据源的工厂,DriverManager的替代,而且是比前者更好的获取数据库连接的方式。