java实现jdbc查询结果集result转换成对应list集合

时间:2022-05-20 07:09:06

代码非常的简单,这里就不多废话了,直接奉上

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static <T> List<T> convertToList(ResultSet rs,Class<T> t) throws SQLException {
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
    int columnCount = md.getColumnCount();
    while (rs.next()) {
      Map<String, Object> rowData = new HashMap<String, Object>();
      for (int i = 1; i <= columnCount; i++) {
        rowData.put(md.getColumnName(i), rs.getObject(i));
      }
      list.add(rowData);
    }
    JSONArray jr = JSONArray.fromObject(list);
    List<T> resultList = JSONArray.toList(jr, t);
    return resultList;
  }

是不是很简单。。给新手参考下的,老鸟们请略过