1、jar包下载:
https://github.com/alibaba/druid/releases
2、导入jar包
2.1创建lib文件夹,复制粘贴进去
2.2
2.3
3、 创建配置文件
文件名称(不可改为其他):druid-config.properties
文件内写数据库连接信息
格式:
initialSize:初始连接数量
maxActive:最大连接数量
实际使用中,建议两个数保持一致;初始就创建好所需资源,保证用户的使用速度和服务器性能;
4、使用
步骤:
- 1.加载属性文件
- 2.获取DateSource数据源对象
- 3.创建数据库连接
package com.jdbc.demo.sample;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.jdbc.demo.common.DbUtils;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
/**
* Druid连接池配置与使用
*/
public class DruidSample {
public static void main(String[] args) {
//1.加载属性文件
Properties properties = new Properties();
String propertyFile = DruidSample.class.getResource("/druid-config.properties").getPath();
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.获取DateSource数据源对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
//3.创建数据库连接
conn = dataSource.getConnection();
pstmt = conn.prepareStatement("select * from table_name 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);
}
}
}
package com.jdbc.demo.common;
import java.sql.*;
public class DbUtils {
/**
* 创建新的数据库连接
*
* @return 新的Connection对象
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection() throws ClassNotFoundException, SQLException {
//1.加载并注册JDBC驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.创建数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true");
return conn;
}
/**
* 关闭连接,释放资源
*
* @param rs 结果集对象
* @param pstmt Statement对象
* @param conn Connection对象
*/
public static void closeConnection(ResultSet rs, PreparedStatement pstmt, Connection conn) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}