3

I'm trying to put the Result Set (DB Query Values) inside a LinkedHashMap>.

Every Iteration of row. The value is getting overriden while putting into DBMap.

<LinkedHashMap<String, String>> rowData = new LinkedHashMap<>();
<LinkedHashMap<Integer, LinkedHashMap<String, String>>> dbData = new LinkedHashMap<>();
while (rset.next()) {

                    for (int col = 1; col < countCol+1; col++) {
                        String colname =rset.getMetaData().getColumnName(col);
                        rowData.put(colname, rset.getString(col));
                    }
                    int rowV = rset.getRow();
                    dbData.put(rowV, rowData);
}

This code is giving me the map of only the last row of the result set for all the keys in dbData Map.

4

2 回答 2

3

您将同一个LinkedHashMap实例(由rowData变量引用)多次放入您的外部Map. 这就是最终数据库行的值覆盖所有先前值的原因。

您必须为循环LinkedHashMap的每次迭代创建一个新实例while

LinkedHashMap<Integer, LinkedHashMap<String, String>> dbData = new LinkedHashMap<>();
while (rset.next()) {
    LinkedHashMap<String, String> rowData = new LinkedHashMap<>();
    for (int col = 1; col < countCol+1; col++) {
        String colname =rset.getMetaData().getColumnName(col);
        rowData.put(colname, rset.getString(col));
    }
    int rowV = rset.getRow();
    dbData.put(rowV, rowData);
}
于 2017-08-09T07:33:13.337 回答
1

很简单:您只有一个rowData 映射 - 使用行数据进行更新。

您必须为每一行创建一个的地图!

换句话说:您当前的代码创建一个映射,该映射会针对每个“行”迭代进行更新。最后,您将同一张地图放入外部地图中。

于 2017-08-09T07:33:44.820 回答