1. 程式人生 > >Java_反射_SQL增刪改查

Java_反射_SQL增刪改查

Java_反射_SQL增刪改查

#Java Bean

package com.hp.beans;
/**
 * Java類 User
 */
public class user {
private Integer uid;
private String uname;
private String upass;
private String isadmin;
    public Integer getUid() {
        return uid;
    }
    public void setUid(Integer uid) {
        this.uid = uid;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getUpass() {
        return upass;
    }
    public void setUpass(String upass) {
        this.upass = upass;
    }
    public String getIsadmin() {
        return isadmin;
    }
    public void setIsadmin(String isadmin) {
        this.isadmin = isadmin;
    }
    @Override
    public String toString() {
        return "user{" +
                "uid=" + uid +
                ", uname='" + uname + '\'' +
                ", upass='" + upass + '\'' +
                ", isadmin='" + isadmin + '\'' +
                '}';
    }
    public user(Integer uid, String uname, String upass, String isadmin) {
        this.uid = uid;
        this.uname = uname;
        this.upass = upass;
        this.isadmin = isadmin;
    }
    public user() {
    }
}

#獲得連結

package com.hp.reflect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 獲取Sql連線的類
 */
public class GetConnection{
    /**
     * 獲取sql的連線物件
     * @return
     */
    public Connection getCon(){
        //定義連線物件
        Connection conn=null;
        try {
            //載入MySql資料庫驅動
            Class.forName("com.mysql.jdbc.Driver");
            //通過DriverManager.getConnection(url,username,password)獲取資料庫的連線
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        //將獲取的資料庫連線返回
        return conn;
    }
}

#增刪改查

package com.hp.reflect;
import com.hp.beans.user;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
 * 反射_sql查詢
 */
public class DaoImpl {
    //定義接收的型別為泛型集合
    public <T> List<T> select(T t) throws SQLException, IllegalAccessException, InstantiationException {
        //Class.getSimpleName()通過泛型獲取物件名
        String sql="select * from "+t.getClass().getSimpleName();
        //例項化List泛型
        List<T> li=new ArrayList<T>();
        //例項化GetConnection類,通過getCon方法獲取Sql的連線
        Connection con = new GetConnection().getCon();
        //通過連線的prepareStatement()的方法執行sql語句
        //呼叫executeQuery()執行查詢獲取查詢的結果集合
        ResultSet res = con.prepareStatement(sql).executeQuery();
        //通過resultSet.getMetadata()將結果集合轉換為ResultMetaData物件
        ResultSetMetaData md = res.getMetaData();
        //獲取結果的列數
        int count = md.getColumnCount();
        //獲取java物件的屬性陣列
        Field[] filds = t.getClass().getDeclaredFields();
        //呼叫next方法遍歷結果集合
        while(res.next()) {
            //將泛型類例項化為物件
            T t2 = (T) t.getClass().newInstance();
            //迴圈泛型物件的屬性值
            for (int i = 0; i < filds.length; i++) {
                //輸出當前的屬性
                System.out.println(filds[i]);
                //迴圈遍歷當前結果集中的物件的屬性
                for (int k = 0; k < count; k++) {
                    //獲取此條資訊的列的名字
                    String columnName = md.getColumnName(k + 1);
                    //判斷結果集中的列名與Java類中的屬性名是否對應
                    if (filds[i].getName().toUpperCase().equals(columnName.toUpperCase())) {
                        //修改類的Accessible為true,使當前屬性可以修改
                        filds[i].setAccessible(true);
                        //res.getObject(列名) 獲取當前這條資訊的列名的資料
                        //呼叫Filed類的set方法,給當前物件賦值
                        filds[i].set(t2, res.getObject(columnName));
                    }
                }
            }
            //將迴圈賦值完成的類新增到集合中
            li.add(t2);
        }
        //返回結果
        return li;
    }
    /**
     * 更新
     * @param t
     * @param <T>
     * @return
     */
    public <T> T update(T t){
        try {
            Field[] filds = t.getClass().getDeclaredFields();
            filds[0].setAccessible(true);
            String tiao="";
            for(int i=1;i<filds.length;i++){
                Field fild=filds[i];
                fild.setAccessible(true);
                if(fild.getType().equals(String.class)) {
                    tiao += fild.getName() + "='" + fild.get(t) + "',";
                }
                else{
                    tiao += fild.getName() + "='" + fild.get(t) + "',";
                }
            }
            tiao=tiao.split(",$")[0];
            String sql="update "+t.getClass().getSimpleName()+" set "+tiao+" where "+filds[0].getName()+" ="+filds[0].get(t);
            System.out.println(sql);
            int i=new GetConnection().getCon().prepareStatement(sql).executeUpdate();
            System.out.println(i);
            if (i>0){
            System.out.println("Successful!");
            }
            else{
                System.out.println("Error!");
            }

        } catch (IllegalAccessException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 新增
     * @param t
     * @param <T>
     * @return
     * @throws IllegalAccessException
     */
    public <T> T insert(T t) throws IllegalAccessException {
        Field[] filds = t.getClass().getDeclaredFields();
        String columnName="";
        String columnValue="";
        for (int i=0;i<filds.length;i++){
            filds[i].setAccessible(true);
            if(filds[i].get(t)==null){
                continue;
            }
            columnName+=filds[i].getName()+",";
            if(filds[i].getType().equals(String.class)){
                columnValue+="'"+filds[i].get(t)+"'"+",";
            }
            else{
                columnValue+=filds[i].get(t)+",";
            }
        }
        columnName=columnName.split(",$")[0];
        columnValue=columnValue.split(",$")[0];
        String sql="insert into "+t.getClass().getSimpleName()+"("+columnName+") values("+columnValue+")";
        System.out.println(sql);
        try {
            int i=new GetConnection().getCon().prepareStatement(sql).executeUpdate();
            if(i>0){
                System.out.println("Successful!");
            }
            else{
                System.out.println("Error!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 反射刪除
     * @param t
     * @param <T>
     * @return
     */
    public <T> T delete(T t) throws SQLException {
        Field fild = t.getClass().getDeclaredFields()[0];
        fild.setAccessible(true);
        try {
            String sql="delete from "+t.getClass().getSimpleName()+" where "+fild.getName()+" = "+fild.get(t);
            System.out.println(sql);
            int i=new GetConnection().getCon().prepareStatement(sql).executeUpdate();
            if(i>0){
                System.out.println("Successful!");
            }
            else{
                System.out.println("Error!");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}