1. 程式人生 > >JDBC(六) 編寫通用的更新和查詢方法

JDBC(六) 編寫通用的更新和查詢方法

對於C(建立),U(更新),D(刪除)都屬於更新操作,對於R(讀取查詢)屬於查詢操作。這裡編寫兩個通用的更新和查詢方法。

更新

更新簡單,只需要傳入對應的sql和sql的佔位符,然後執行更新就可以了。

/**
     * @return 返回影響的行數
     * @param connection
     * @param sql
     * @param args
     */
    public int update(String sql, Object... args) {
        int row = 0;
        try {
            Connection connection = JDBCUtils.getConnection();
            PreparedStatement preparedStatement = connection
                    .prepareStatement(sql);
            // 填充sql的佔位符
for (int i = 0; i < args.length; i++) { preparedStatement.setObject(i + 1, args[i]); } row = preparedStatement.executeUpdate(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return
row; }

查詢

對於查詢,比較麻煩的是,返回的結果集的處理,可以遍歷結果集然後建立對應的javabean,然後返回。但是對於不同的javabean,對應的屬性並不知道,這裡可以從結果集中獲取查詢結果的別名(別名和javabean的屬性名對應),然後利用反射建立物件併為屬性賦相應的值,返回一個javabean的物件。

public <T> T query(Class<T> clazz, String sql, Object... args) {

        T entity = null;

        Connection connection = null
; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // 獲取resultSet connection = JDBCUtils.getConnection(); preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { preparedStatement.setObject(i + 1, args[i]); } resultSet = preparedStatement.executeQuery(); // 獲取resultSetMetaData ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); // 建立一個MAP 鍵 :SQL查詢得到的列的別名,別名和javaBean的屬性名對應 值:對應列的值 Map<String, Object> values = new HashMap<String, Object>(); // 處理結果集,利用resultSetMetaData填充Map while (resultSet.next()) { for (int i = 0; i < resultSetMetaData.getColumnCount(); i++) { String columnLable = resultSetMetaData .getColumnLabel(i + 1); Object columnValue = resultSet.getObject(i + 1); values.put(columnLable, columnValue); } } // 如果map不為空,利用反射建立物件 if (values.size() > 0) { // 反射建立物件 entity = clazz.newInstance(); // 遍歷Map ,利用反射為屬性賦值 for (Map.Entry<String, Object> entry : values.entrySet()) { String fieldName = entry.getKey(); Object value = null; // 因為java中和mysql中資料型別對應不一致 // mysql中int對應JAVA中的long,所以當查詢出int型資料的時候需要轉換 if (entry.getValue() instanceof Long) { value = Integer.parseInt(entry.getValue().toString()); } else { value = entry.getValue(); } // ReflectionUtils.setFieldValue(entity, fieldName, value); Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); field.set(entity, value); } } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return entity; }

建立兩個javabean,對應資料庫中的表
user.java:

package com.aaa.entity;

import java.sql.Date;

public class User {

    private int userId;
    private String userName;
    private String userPassword;
    private Date userBirth;

    public User(int userId, String userName, String userPassword, Date userBirth) {
        super();
        this.userId = userId;
        this.userName = userName;
        this.userPassword = userPassword;
        this.userBirth = userBirth;
    }

    public User() {

    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public Date getUserBirth() {
        return userBirth;
    }

    public void setUserBirth(Date userBirth) {
        this.userBirth = userBirth;
    }

    @Override
    public String toString() {
        return "User [userId=" + userId + ", userName=" + userName
                + ", userPassword=" + userPassword + ", userBirth=" + userBirth
                + "]";
    }

}

customer.java:

package com.aaa.entity;

public class Customer {
    private int customerId;
    private String customerName;
    private String customerPassword;

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCustomerPassword() {
        return customerPassword;
    }

    public void setCustomerPassword(String customerPassword) {
        this.customerPassword = customerPassword;
    }

    public Customer(int customerId, String customerName, String customerPassword) {
        super();
        this.customerId = customerId;
        this.customerName = customerName;
        this.customerPassword = customerPassword;
    }

    public Customer() {
        super();
    }

    public String toString() {
        return "Customer [customerId=" + customerId + ", customerName="
                + customerName + ", customerPassword=" + customerPassword + "]";
    }

}

測試:

public void testQuery() {
        String sql = "SELECT user_id userId,user_name userName,user_password userPassword,user_birth userBirth FROM user WHERE user_id = ?";
        User user = query(User.class, sql, 2);
        System.out.println(user);

        sql = "SELECT customer_id customerId,customer_name customerName,customer_password customerPassword FROM customer WHERE customer_id = ? AND customer_name =?";
        Customer customer = query(Customer.class, sql, 2, "marry");
        System.out.println(customer);
    }

結果:這裡寫圖片描述

總結:在查詢的時候,只需要傳入sql和sql佔位符以及對應的class,就可以直接返回對應的物件,而不需要為每一個Javabean建立對應的方法。