尚硅谷之JDBC

2.6工具类通用的查询多个实体的方法

         //通用的查询方法之二:查询多行,即多个对象

         //Class<T> clazz:用来创建实例对象,获取对象的属性,并设置属性值

         /**

          * 执行查询操作的SQL语句,SQL可以带参数(?)

          * @param clazz Class 查询的结果需要封装的实体的Class类型,例如:学生Student,商品Goods,订单Order

          * @param sql String 执行查询操作的SQL语句

          * @param args Object... 对应的每个?设置的值,顺序要与?对应

          * @return ArrayList<T> 封装了查询结果的集合

          * @throws Exception

          */

         public static <T> ArrayList<T> getList(Class<T> clazz,String sql,Object... args)throws Exception{

                   //1、注册驱动,不用了

                   //2、获取连接

                   Connection conn = JDBCUtils.getConnection();

 

                   //3、对sql进行预编译

                   PreparedStatement pst = conn.prepareStatement(sql);

 

                   //4、对?进行设置值

                   if(args!=null && args.length>0){

                            for (int i = 0; i < args.length; i++) {

                                     pst.setObject(i+1, args[i]);

                            }

                   }

 

                   //5、执行sql

                   ResultSet rs = pst.executeQuery();

                   //获取结果集的元数据

                   ResultSetMetaData metaData = rs.getMetaData();

                   //获取结果中总列数

                   int count = metaData.getColumnCount();

 

                   //创建集合对象

                   ArrayList<T> list = new ArrayList<T>();

 

                   while(rs.next()){//遍历的行

                            //1、每一行是一个对象

                            T obj = clazz.newInstance();

 

                            //2、每一行有很多列

                            //for的作用是为obj对象的每一个属性设置值

                            for (int i = 0; i < count; i++) {

                                     //(1)每一列的名称

                                     String fieldName = metaData.getColumnLabel(i+1);//获取第几列的名称,如果有别名获取别名,如果没有别名获取列名

                                     //(2)每一列的值

                                     Object value = rs.getObject(i+1);//获取第几列的值

                                     //(3)获取属性对象

                                     Field field = clazz.getDeclaredField(fieldName);

                                     //(4)设置可见性

                                     field.setAccessible(true);

                                     //(5)设置属性值

                                     field.set(obj, value);

                            }

 

                            //3、把obj对象放到集合中

                            list.add(obj);

                   }

 

                   //6、释放资源

                   JDBCUtils.closeQuietly(rs,pst,conn);

 

                   //7、返回结果

                   return list;

         }