在while循环中将每一行数据封装成对象,将其存储到集合当中,使用Lambda表达式输出数据
代码如下:
//测试查询多条数据
public void testManyQueryForStudent(){
String sql="select *from student where Sdept=?";
List<Student> is = manyQueryForStudent(sql, "IS");
is.forEach(System.out::println);
}
//查询多条数据
public List<Student> manyQueryForStudent(String sql,Object...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1.获取连接
conn = JDBCutils.getConnection();
//2.编译sql语句,返回prepareStatement实例
ps = conn.prepareStatement(sql);
//3.通过循环设置占位符的值
for(int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
//4.执行并返回结果集
rs = ps.executeQuery();
//获取结果集的元数据
ResultSetMetaData rsm = rs.getMetaData();
//通过ResultSetMetaData获取结果集中的列数
int count = rsm.getColumnCount();
ArrayList<Student> list = new ArrayList<Student>();
while (rs.next()){
//如果有值,创建一个student对象
Student student = new Student();
for(int i=0;i<count;i++){
Object studentValue = rs.getObject(i + 1);
//获取每一个列的列名
String studentName = rsm.getColumnLabel(i + 1);
//通过反射studentName属性,赋值为studentValue
Field filed = Student.class.getDeclaredField(studentName);
//属性可能是私有的,通过setAccessible(true)访问
filed.setAccessible(true);
filed.set(student,studentValue);
}
list.add(student);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCutils.closeResource(ps,conn,rs);
}
return null;
}
效果如下: