JDBC封裝
前言
正如在前面的小節中看到的,原生的JDBC的操作其實是比較繁瑣的,而且其中有很多的重復性代碼,這個時候,我們可以考慮自己對JDBC進行一個簡單的封裝,封裝成自己想要的,比較方便的小工具
封裝JDBC
為了使得編輯參數更加方便,首先將數據庫連接參數抽取出來放在配置文件jdcb.properties
中
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.user=root
jdbc.password=huanfeng
然后在類加載的時候加載該配置文件,并且注冊驅動類信息
private static Properties properties;
// 使用靜態代碼塊保證在類加載的時候立即加載對應的配置文件
static {
properties = new Properties();
try {
InputStream ins = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(ins);
System.out.println("load config file finish");
Class.forName(properties.getProperty("jdbc.driver"));
} catch (FileNotFoundException e) {
System.out.println("jdbc config file not found " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("jdbc class not found " + e.getMessage());
}
}
接著封裝獲取連接對象getConnection()
/**
* 獲得數據庫連接Connection
* @return Connection 數據庫連接
*/
private static Connection getConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(
properties.getProperty("jdbc.url"),
properties.getProperty("jdbc.user"),
properties.getProperty("jdbc.password"));
} catch (SQLException e) {
System.out.println("cannot get connection " + e.getMessage());
}
return connection;
}
然后封裝關閉各種資源的方法close()
/**
* 關閉connection
* @param connection 連接池對象
*/
private static void close(Connection connection){
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 關閉Statement
* @param statement
*/
private static void close(Statement statement){
if (statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 關閉ResultSet
* @param resultSet
*/
private static void close(ResultSet resultSet){
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 關閉Connection 以及Statement
* @param connection
* @param statement
*/
private static void close(Connection connection, Statement statement){
close(connection);
close(statement);
}
/**
* 關閉Connection,Statement以及ResultSet
* @param connection
* @param statement
* @param resultSet
*/
private static void close(Connection connection, Statement statement, ResultSet resultSet){
close(connection, statement);
close(resultSet);
}
接著封裝更新方法,正如所知道的,更新包括插入、刪除、修改,所以可以將這些操作封裝在一個方法即可
/**
* 更新操作
* @param sql 執行的SQL語句
* @param param 對應的參數列表
* @return true 更新成功, false 更新失敗
*/
public static boolean update(String sql, Object[] param){
PreparedStatement preparedStatement = null;
Connection connection = getConnection();
try {
preparedStatement = connection.prepareStatement(sql);
if (settingParams(preparedStatement, param) == false){
return false;
}
int result = preparedStatement.executeUpdate();
if (result > 0){
return true;
}
return false;
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(connection, preparedStatement);
}
return false;
}
上面封裝了一個方法settingParams()
,作用是利用元數據信息,根據SQL語句中的占位符個數,將對應的參數注入進去
/**
* 設置參數
* @param preparedStatement Statement對象
* @param param 參數列表
* @return
* @throws SQLException
*/
private static boolean settingParams(PreparedStatement preparedStatement, Object[] param) throws SQLException {
if (param != null && param.length > 0){
// 獲取ParameterMetaData
ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
// 獲得SQL中占位符個數
int paramCount = parameterMetaData.getParameterCount();
// 占位符個數與參數個數不一致,返回false表示出錯
if (paramCount != param.length){
return false;
}
// 設置對應的參數信息
for (int i = 0; i < paramCount; i++){
preparedStatement.setObject(i+1, param[i]);
}
}
return true;
}
由于查詢返回的類型非常多,這里只是封裝兩個常用的方法,一個是queryForBean()
返回單個對象,一個是queryForList()
返回List,這里需要注意的是,由于只是簡單的封裝,所以沒有做對象屬性名與數據表列名的映射,所以需要保證屬性名與列名相同,為了更加方便進行操作,使用了泛型機制,并且使用了Apache的BeanUtils工具進行屬性的注入操作,BeanUtils的Maven配置如下所示
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
/**
* 獲取單個Bean
* @param sql 執行SQL語句
* @param param 對應的參數列表
* @param clazz 所要獲取的對象的類型
* @param <T> 對象的類型
* @return
*/
public static <T> T queryForBean(String sql, Object[] param, Class<T> clazz){
Connection connection = getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(sql);
if (settingParams(preparedStatement, param) == false){
return null;
}
resultSet = preparedStatement.executeQuery();
if (resultSet == null){
return null;
}
if (resultSet.next()){
// 利用反射機制創建對象
T data = clazz.newInstance();
// 獲得ResultSetMetaData
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
// 獲得列的數量
int columnCount = resultSetMetaData.getColumnCount();
for (int i = 0; i < columnCount; i++){
// 獲得對應的列的名稱
String name = resultSetMetaData.getColumnName(i + 1);
// 獲得對應的列的值
Object rData = resultSet.getObject(name);
// 使用BeanUtils工具對屬性進行注入
BeanUtils.copyProperty(data, name, rData);
}
return data;
}else {
return null;
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
close(connection, preparedStatement, resultSet);
}
return null;
}
/**
* 獲取Bean并且封裝成List
* @param sql 執行SQL語句
* @param param 對應的參數列表
* @param clazz 所要獲取的對象的類型
* @param <T> 對象的類型
* @return list
*/
public static <T> List<T> queryForList(String sql, Object[] param, Class<T> clazz){
Connection connection = getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(sql);
if (settingParams(preparedStatement, param) == false){
return null;
}
resultSet = preparedStatement.executeQuery();
if (resultSet == null){
return null;
}
List<T> results = new ArrayList<>();
while (resultSet.next()){
// 創建對象
T data = clazz.newInstance();
// 獲得ResultSetMetaData
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
// 獲得列的數量
int columnCount = resultSetMetaData.getColumnCount();
for (int i = 0; i < columnCount; i++){
// 獲得對應的列的名稱
String name = resultSetMetaData.getColumnName(i + 1);
// 獲得對應的列的值
Object rData = resultSet.getObject(name);
// 使用BeanUtils工具對屬性進行注入
BeanUtils.copyProperty(data, name, rData);
}
results.add(data);
}
return results;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
close(connection, preparedStatement, resultSet);
}
return null;
}
至此,通過簡單的封裝,一個簡單的JDBC操作工具就封裝好了,這樣,當需要的時候就可以非常方便地使用了,而且,當需要其他返回類型的時候,基本上只要按照上面的思路進行處理即可。
完整的代碼如下所示
package cn.xuhuanfeng.jdbc;
import org.apache.commons.beanutils.BeanUtils;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* Created by Huanfeng.Xu on 2017-07-09.
*/
public class JDBCUtils {
private static Properties properties;
static {
properties = new Properties();
try {
InputStream inputStream = JDBCUtils.class.getResourceAsStream("jdbc.properties");
InputStream ins = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(ins);
System.out.println("load config file finish");
Class.forName(properties.getProperty("jdbc.driver"));
} catch (FileNotFoundException e) {
System.out.println("jdbc config file not found " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("jdbc class not found " + e.getMessage());
}
}
/**
* 獲得數據庫連接Connection
* @return Connection 數據庫連接
*/
private static Connection getConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(
properties.getProperty("jdbc.url"),
properties.getProperty("jdbc.user"),
properties.getProperty("jdbc.password"));
} catch (SQLException e) {
System.out.println("cannot get connection " + e.getMessage());
}
return connection;
}
/**
* 設置參數
* @param preparedStatement Statement對象
* @param param 參數列表
* @return
* @throws SQLException
*/
private static boolean settingParams(PreparedStatement preparedStatement, Object[] param) throws SQLException {
if (param != null && param.length > 0){
ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
int paramCount = parameterMetaData.getParameterCount();
if (paramCount != param.length){
return false;
}
for (int i = 0; i < paramCount; i++){
preparedStatement.setObject(i+1, param[i]);
}
}
return true;
}
/**
* 更新操作
* @param sql 執行的SQL語句
* @param param 對應的參數列表
* @return
*/
public static boolean update(String sql, Object[] param){
PreparedStatement preparedStatement = null;
Connection connection = getConnection();
try {
preparedStatement = connection.prepareStatement(sql);
if (settingParams(preparedStatement, param) == false){
return false;
}
int result = preparedStatement.executeUpdate();
if (result > 0){
return true;
}
return false;
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(connection, preparedStatement);
}
return false;
}
/**
* 獲取單個Bean
* @param sql 執行SQL語句
* @param param 對應的參數列表
* @param clazz 所要獲取的對象的類型
* @param <T> 對象的類型
* @return bean
*/
public static <T> T queryForBean(String sql, Object[] param, Class<T> clazz){
Connection connection = getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(sql);
if (settingParams(preparedStatement, param) == false){
return null;
}
resultSet = preparedStatement.executeQuery();
if (resultSet == null){
return null;
}
if (resultSet.next()){
T data = clazz.newInstance();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
for (int i = 0; i < columnCount; i++){
String name = resultSetMetaData.getColumnName(i + 1);
Object rData = resultSet.getObject(name);
BeanUtils.copyProperty(data, name, rData);
}
return data;
}else {
return null;
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
close(connection, preparedStatement, resultSet);
}
return null;
}
/**
* 獲取Bean并且封裝成List
* @param sql 執行SQL語句
* @param param 對應的參數列表
* @param clazz 所要獲取的對象的類型
* @param <T> 對象的類型
* @return list
*/
public static <T> List<T> queryForList(String sql, Object[] param, Class<T> clazz){
Connection connection = getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(sql);
if (settingParams(preparedStatement, param) == false){
return null;
}
resultSet = preparedStatement.executeQuery();
if (resultSet == null){
return null;
}
List<T> results = new ArrayList<>();
while (resultSet.next()){
T data = clazz.newInstance();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
for (int i = 0; i < columnCount; i++){
String name = resultSetMetaData.getColumnName(i + 1);
Object rData = resultSet.getObject(name);
BeanUtils.copyProperty(data, name, rData);
}
results.add(data);
}
return results;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
close(connection, preparedStatement, resultSet);
}
return null;
}
/**
* 關閉connection
* @param connection 連接池對象
*/
private static void close(Connection connection){
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 關閉Statement
* @param statement
*/
private static void close(Statement statement){
if (statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 關閉ResultSet
* @param resultSet
*/
private static void close(ResultSet resultSet){
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 關閉Connection 以及Statement
* @param connection
* @param statement
*/
private static void close(Connection connection, Statement statement){
close(connection);
close(statement);
}
/**
* 關閉Connection,Statement以及ResultSet
* @param connection
* @param statement
* @param resultSet
*/
private static void close(Connection connection, Statement statement, ResultSet resultSet){
close(connection, statement);
close(resultSet);
}
}