在使用数据库的过程中,我们有很多操作都是重复的,比如连接数据库、关闭资源等等,其实在数据库做Java开发过程中,除了我们每次的SQL语言不同外,其他的大部分操作都是重复的,这里简单封装了两个类
一、JDBC工具类
内容:
1.数据库连接对象java.sql.Connection获取过程
2.关闭资源
话不多说,看代码
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JdbcUtil {
private static String url = null;
private static String user = null;
private static String password = null;
static {
try {
//Properties实现类,里面的数据保存形式都是键值对形式
Properties properties = new Properties();
//字节输入流加载db.properties
properties.load(new FileInputStream("./src/db.properties"));
String driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Class.forName(driverClass);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 返回数据库连接对象,连接失败返回null
*
* @return java.sql.Connection 数据库连接对象
*/
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(Connection connection) {
close(connection, null, null);
}
public static void close(Connection connection, Statement statement) {
close(connection, statement, null);
}
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (connection != null) {
connection.close();
}
if (statement != null) {
statement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
二、数据库操作基类
内容:
1.完成通用的更新方法,满足inset、update、delete操作
2.完成通用的查询方法,满足select
这里需要使用BeanUtils,需要导入jar包,链接放在文章最后
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* BaseDao 数据库操作基类
*
*/
public class BaseDao {
/**
* 通用的更新方法
*
* @param sql String 类型的SQL语句,需要执行的方法
* @param parameters 对应当前SQL语句的参数列表,Object数组
* @return SQL语句执行数据库受到影响的行数
*/
public int update(String sql, Object[] parameters) {
int affectedRows = 0;
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JdbcUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
int parameterCount = preparedStatement.getParameterMetaData().getParameterCount();
/*
parameterCount 参数个数不能为0
parameters != null 参数数组不为null,因为存在当前方法没有参数,数组传入null
parameterCount == parameters.length 参数个数和传入的Object类型参数容量一致
*/
if (parameterCount != 0 && parameters != null && parameterCount == parameters.length) {
for (int i = 0; i < parameters.length; i++) {
preparedStatement.setObject(i + 1, parameters[i]);
}
}
//执行SQL语句
affectedRows = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(connection, preparedStatement);
}
return affectedRows;
}
/**
* 通用的查询方法,查询cls指定数据类型,返回一个List集合
*
* @param sql SQL语句
* @param parameters 对应的当钱SQL语句的参数
* @param cls 指定数据类型,同时提供Class对象,便于反射操作,约束泛型类型
* @param <T> 泛型占位符
* @return 指定数据类型的List集合
*/
public <T> List<T> query(String sql, Object[] parameters, Class<T> cls) {
ResultSet resultSet = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
List<T> list = new ArrayList<>();
try {
connection = JdbcUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
int parameterCount = preparedStatement.getParameterMetaData().getParameterCount();
/*
parameterCount 参数个数不能为0
parameters != null 参数数组不为null,因为存在当前方法没有参数,数组传入null
parameterCount == parameters.length 参数个数和传入的Object类型参数容量一致
*/
if (parameterCount != 0 && parameters != null && parameterCount == parameters.length) {
for (int i = 0; i < parameters.length; i++) {
preparedStatement.setObject(i + 1, parameters[i]);
}
}
resultSet = preparedStatement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
T t = cls.getConstructor().newInstance();
for (int i = 1; i <= columnCount; i++) {
String fieldName = metaData.getColumnName(i);
Object value = resultSet.getObject(fieldName);
BeanUtils.setProperty(t, fieldName, value);
}
list.add(t);
}
} catch (SQLException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(connection, preparedStatement, resultSet);
}
return list.size() != 0 ? list : null;
}
}
如果想多了解BeanUtils使用可以参考我的测试代码:
https://blog.csdn.net/weixin_44009147/article/details/105078644
jar包链接(永久有效):
链接:https://pan.baidu.com/s/1GCOzx2831Hk0xrorL9Z7eA
提取码:efxv