Druid是目前最好的数据库连接池,是阿里出品,淘宝和支付宝专用数据库连接池,对Oracle和MySql做了特别优化。
使用Druid的使用步骤
1.导入druid的jar包(官网下载)
druid-1.2.1.jar Central Repository: com/alibaba/druid
mysql-connector-java-8.0.22.jar MySQL :: Download Connector/J
2.在src下创建Druid的配置文件druid.properties
必填选项:驱动类名、url、账号、密码
# 驱动类名 mysql5.7之前使用com.mysql.jdbc.Driver
driverClassName = com.mysql.cj.jdbc.Driver
# url 账号 密码
url = jdbc:mysql://localhost:3306/myFirstDatabase
username = root
password = 123456
# 初始化连接数 默认0
initialSize = 10
# 最大连接数 默认8
maxActive = 30
# 最小闲置数
minIdle = 10
# 获取连接的最大等待时间,单位是毫秒 默认-1
maxWait = 2000
# 缓存PreparedStatement,默认false
poolPreparedStatement = true
# 缓存PreparedStatement的最大数量,默认-1(不缓存) 大于0 会自动开启缓存PreparedStatement
maxOpenPreparedStatement = 20
3.代码操作
1、创建配置文件对象
Properties pro = new Properties();
2、通过反射获取druid配置文件
pro.load(DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"));
3、通过数据源工厂创建数据源
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
4、通过数据源获取连接对象
Connection conn = ds.getConnection();
5、连接关闭后自动进行回收(之后再获取时,就会获取到被回收的对象)
conn.close();
//使用被回收的对象
Connection conn1 = ds.getConnection();
conn1.close();
Druid工具类的封装
package util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class DBUtil {
//数据源
private static DataSource dataSource = null;
static {
Properties pro = new Properties();
try {
pro.load(DBUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
dataSource = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接
* @return 数据库连接
*/
private static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 增删改
* @param sql sql语句
* @param index char类型在参数中位置
* @param params 参数
* @return
*/
public static int executeUpdate(String sql,int index,Object ... params){
Connection conn = getConnection();
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
//设置占位符
for(int i=0;i< params.length;i++){
//对char类型单独处理
if(index == (i+1)){
char c = (char)params[i];
ps.setString(i+1,c+"");
continue;
}
ps.setObject(i+1,params[i]);
}
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
close(null,ps,conn);
}
return 0;
}
/**
* 查询
* @param tclass 实体类
* @param sql sql语句
* @param index char类型在参数中的位置
* @param params 参数
* @param <T> 实体类对象
* @return
*/
public static <T> List<T> executeQuery(Class<T> tclass,String sql,int index,Object ... params){
List<T> list = null;
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
//设置占位符
for(int i=0;i<params.length;i++){
//对char类型单独处理
if(index == (i+1)){
char c = (char)params[i];
ps.setString(i+1,c+"");
continue;
}
ps.setObject(i+1,params[i]);
}
rs = ps.executeQuery();
list = new ArrayList<>();
while (rs.next()){
T obj = tclass.newInstance();
//读取类型中的所有属性
Field[] fields = tclass.getDeclaredFields();
for(int j=0;j< fields.length;j++){
String fieldName = fields[j].getName();
Class typeClass = fields[j].getType();
//获取字段中大写字母的位置,进行截取
fieldName = getColName(fieldName);
//将属性设置为可以访问
fields[j].setAccessible(true);
//进行类型判断
if((typeClass+"").equals("char")){
char value = rs.getString(fieldName).charAt(0);
//给属性赋值
fields[j].set(obj,value);
}else if((typeClass+"").equals("double")){
double value = rs.getDouble(fieldName);
fields[j].set(obj,value);
}else if((typeClass+"").equals("class java.sql.Date")){
Date value = rs.getDate(fieldName);
fields[j].set(obj,value);
}else{
Object value = rs.getObject(fieldName);
//给属性赋值
fields[j].set(obj,value);
}
}
list.add(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally{
close(rs,ps,conn);
}
return list;
}
//释放资源
public static void close(ResultSet rs, Statement state, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(state != null){
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//获取数据源
public static DataSource getDataSource(){
return dataSource;
}
//列名转换
private static String getColName(String fieldName){
char[] arrUp = new char[5];
int k = 0;
for(int i=0;i<fieldName.length();i++){
char c = fieldName.charAt(i);
if(65<= c && c<=90){
arrUp[k] = c;
k++;
}
}
if(k !=0) {
String[] str = fieldName.split("[A-Z]");
fieldName = str[0];
for (int i = 0; i < str.length - 1; i++) {
fieldName += "_" + (arrUp[i] + "").toLowerCase() + str[i + 1];
}
//System.out.println(fieldName);
}
return fieldName;
}
}