Druid.properties 数据库配置
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///orcHr
username=root
password = root
# 连接数
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000
DruidUtils.java Druid连接池封装类
package cn.demo01.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.util.*;
/**
* @Author Jiafang Wen
* @Date 2023-10-29 22:40
* @Version 1.0
*/
public class DruidUtils {
// 1.定义成员变量 DataSource
private static DataSource ds;
private static Connection conn = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
static {
try {
// 1.加载配置文件
Properties pro = new Properties();
pro.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
// 2.获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
// 执行select 语句
public static List getRsList(String sql) {
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
List rsList = convertList(rs);
return rsList;
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
close(rs, ps, conn);
}
}
// Resultset 结果集转为List数据
private static List convertList(ResultSet rs) throws SQLException {
List list = new ArrayList();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
while (rs.next()) {
Map rowData = new HashMap();
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
return list;
}
// 执行 insert update delete 语句
public static int excute(String sql) {
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
int i = ps.executeUpdate();
return i;
} catch (SQLException e) {
e.printStackTrace();
return 0;
} finally {
close(ps, conn);
}
}
/**
* 释放资源
*/
public static void close(PreparedStatement ps, Connection conn) {
close(null, ps, conn);
}
public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();// 归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 获取连接池方法
*/
public static DataSource getDataSource() {
return ds;
}
}