使用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;
    }
posted @ 2020-12-06 19:55  饶滕龙  阅读(90)  评论(0)    收藏  举报