jdbc中查詢封裝——反射,jdbc封裝反射

來源:互聯網
上載者:User

jdbc中查詢封裝——反射,jdbc封裝反射

在使用原生jdbc時候使用查詢語句大同小異,因此在這裡使用反射將jdbc中查詢語句進行封裝

查詢單條語句
查詢多條語句

package src.jdbcTest;import java.lang.reflect.Field;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import org.apache.log4j.Logger;/** *  * @author chencong * @Time 2017年8月3日 下午12:37:55 * @TODO 通過反射返回單條記錄和多行記錄 */public class DBUtils {    private static final String DRIVER_URL = "jdbc:sqlserver://localhost:1433;DataBaseName=mangerQQSys";    private static final String DRIVER_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";    private static final String DB_USER = "sa";    private static final String DB_PASSWORD = "123456";    private Connection connection = null;    private PreparedStatement preparedStatement = null;    private ResultSet resultSet = null;    public DBUtils() {    }    {        try {            Class.forName(DRIVER_NAME);            connection = DriverManager.getConnection(DRIVER_URL, DB_USER, DB_PASSWORD);        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (SQLException e) {            e.printStackTrace();        }    }    public Connection getConnection() {        return connection;    }    /**     * 關閉資料庫連接     *      * @param connection     * @param ptStatement     * @param resultSet     */    public void closeAll(Connection connection, PreparedStatement ptStatement, ResultSet resultSet) {        try {            if (connection != null) {                connection.close();            }            if (ptStatement != null) {                ptStatement.close();            }            if (resultSet != null) {                ptStatement.close();            }        } catch (SQLException e) {            e.printStackTrace();        }    }    /**     * 關閉資料庫連接     *      * @param ptStatement     * @param resultSet     */    public void closeAll(PreparedStatement ptStatement, ResultSet resultSet) {        try {            if (ptStatement != null) {                ptStatement.close();            }            if (resultSet != null) {                ptStatement.close();            }        } catch (SQLException e) {            e.printStackTrace();        }    }    /**     * 反射機制 返回單條記錄 T     *      * @param sql     * @param params     * @param clazz     * @return     * @throws Exception     */    public <T> T selectSimpleResult(String sql, List<Object> params, Class<T> clazz) throws Exception {        if (connection == null) {            return null;        }        if (sql == null || clazz == null) {            return null;        }        T resultObject = null;        int index = 1;        preparedStatement = connection.prepareStatement(sql);        if (params != null && !params.isEmpty()) {            for (int i = 0; i < params.size(); i++) {                preparedStatement.setObject(index, params.get(i));                index++;            }        }        resultSet = preparedStatement.executeQuery();        ResultSetMetaData metaData = resultSet.getMetaData();        int couLength = metaData.getColumnCount();        while (resultSet.next()) {            // 通過反射的到一個泛型對象            resultObject = clazz.newInstance();            for (int i = 0; i < couLength; i++) {                String colName = metaData.getColumnName(i + 1);                Object colValue = resultSet.getObject(colName);                if (colValue == null) {                    colValue = "";                }                Field field = clazz.getDeclaredField(colName);                field.setAccessible(true); // 取消Java檢查機制 開啟存取權限                field.set(resultObject, colValue);            }        }        return resultObject;    }    /**     * 查詢多條記錄     *      * @param sql     *            將要執行的sql語句     * @param params     * @param clazz     * @return     * @throws Exception     */    public <T> List<T> selectMoreResult(String sql, List<Object> params, Class<T> clazz) throws Exception {        if (connection == null) {            return null;        }        if (sql == null || clazz == null) {            return null;        }        List<T> list = new ArrayList<T>();        int index = 1;        preparedStatement = connection.prepareStatement(sql);        if (params != null && !params.isEmpty()) {            for (int i = 0; i < params.size(); i++) {                System.out.println(index + ":" + params.get(i));                preparedStatement.setObject(index, params.get(i));                index++;            }        }        resultSet = preparedStatement.executeQuery();        ResultSetMetaData metaData = resultSet.getMetaData();        int colLength = metaData.getColumnCount();        while (resultSet.next()) {            // 通過反射建立實體            T resultObject = clazz.newInstance();            for (int i = 0; i < colLength; i++) {                String colName = metaData.getColumnName(i + 1);                Object colValue = resultSet.getObject(colName);                if (colValue == null) {                    colValue = "";                }                Field field = clazz.getDeclaredField(colName);                field.setAccessible(true);                field.set(resultObject, colValue);            }            list.add(resultObject);        }        return list;    }}
聰聰的獨立部落格

聰聰的獨立部落格 ,一個喜歡技術,喜歡鑽研的95後。

  • Blog@ccoder’s blog
  • CSDN@ccoder
  • Github@ccoder
  • Email@ccoder or Gmail@ccoder
著作權聲明:本文為博主原創文章,未經博主允許不得轉載,轉載請註明出處。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.