在使用數據庫的過程中,我們有很多操作都是重複的,比如連接數據庫、關閉資源等等,其實在數據庫做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