使用java.sql.ResultSet中的列名和列值构建映射

时间:2016-11-19 19:16:35

标签: java jdbc

我有以下代码段:

    Connection connection = getConnection(schemaName);
    Statement stmt = connection.createStatement();
    String sql = "SELECT * FROM " + tableName;
    ResultSet rs = stmt.executeQuery(sql);

现在我想要实现的是构建一个

Map<String , List<String>>

其中key是columnName,value是columnValues的列表。这是我的代码:

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();

    List<String> columnNames = new LinkedList<>();
    for (int i = 1; i <= columnCount; i++) {
        columnNames.add(rsmd.getColumnName(i));
    }

    Map<String, List<String>> columnNameToValuesMap = new HashMap<String, List<String>>();

    for (String columnName : columnNames) {
        List<String> values = new ArrayList<>();
        try {
            while (rs.next()) {
                values.add(rs.getString(columnName));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        columnNameToValuesMap.put(columnName, values);
    }

问题是在第一次columnName迭代后,rs.next()为空。所以基本上结果映射只包含第一列的值。如何为每次迭代重用相同的resultSet?为什么它在第一个之后就空了?

1 个答案:

答案 0 :(得分:2)

您可以按照以下步骤操作:

(1)使用列名为键的空columnNameToValuesMap个对象初始化list

(2)使用resultset

迭代rs.next()

(3)使用for循环获取每个列数据并添加到list values对象

(4)将list列数据添加到columnNameToValuesMap对象

您可以在下面的代码中添加评论:

List<String> columnNames = new LinkedList<>();
Map<String,List<String>> columnNameToValuesMap=new HashMap<String, List<String>>();

 for (int i = 1; i <= columnCount; i++) {
        String columnName = rsmd.getColumnName(i);
        columnNames.add(columnName);

        //Load the Map initially with keys(columnnames) and empty list
        columnNameToValuesMap.put(columnName, new ArrayList());
 }

 try {
    while (rs.next()) { //Iterate the resultset for each row

      for (String columnName : columnNames) {
         //Get the list mapped to column name
         List<String> columnDataList = columnNameToValuesMap.get(columnName);

          //Add the current row's column data to list
          columnDataList.add(rs.getString(columnName));

          //add the updated list of column data to the map now
          columnNameToValuesMap.put(columnName, columnDataList);
        }
     }
 } catch (SQLException e) {
    e.printStackTrace();
}