1. 程式人生 > 實用技巧 >使用PrepareStatement實現針對於不同表的查詢操作涉及到泛型和反射技術(返回的結果集是多行多列)

使用PrepareStatement實現針對於不同表的查詢操作涉及到泛型和反射技術(返回的結果集是多行多列)

使用PrepareStatement實現針對於不同表的查詢操作涉及到泛型和反射技術(返回的結果集是多行多列)

執行結果截圖:

資料庫對應的兩張表


測試程式碼:

    @Test
    public void testGetQueryTablesCommonValues(){
        String sql="select id,name,birth,email from customer where id in(?,?,?)";
        List<Customer> list = Common.getQueryTablesCommonValues(Customer.class, sql, 1, 2, 3);
        for(Customer cus:list){
            System.out.println(cus);
        }
        System.out.println("---------------------------------");
        String sql1="select order_id orderId ,order_name orderName,order_date orderDate from `order` where order_id in(?,?,?)";
        List<Order> list1 = Common.getQueryTablesCommonValues(Order.class, sql1, 1, 2, 3);
        for(Order order:list1){
            System.out.println(order);
        }
    }

功能程式碼:

  public static <T> List<T> getQueryTablesCommonValues(Class<T> clazz, String sql, Object... args) {
        List<T> list= null;
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            list = new ArrayList<>();
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            rs = ps.executeQuery();
            while(rs.next()){
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnCount = rsmd.getColumnCount();
                T t = clazz.newInstance();
                for(int i=0;i<columnCount;i++){
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Object objectValue = rs.getObject(i + 1);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,objectValue);
                }
                list.add(t);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection,ps,rs);
        }
        return list;
    }