- 借助bean的办法
List<Person> list = new ArrayList<Person>();
Connection conn = getConn();
String sql = "select * from student_info";
PreparedStatement pst;
try {
pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while(rs.next()){
Person person = new Person();
person.setName(rs.getString(2));
person.setSex(rs.getString(3));
person.setAge(rs.getString(4));
list.add(person);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
即可将查出来的ResultSet转为List。
2. 借助ResultSetMetaData 和Map
private static List convertList(ResultSet rs) throws SQLException {
List list = new ArrayList();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
while (rs.next()) {
Map rowData = new HashMap();
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
return list;
}