javasqlresultsetsqlresultsetmapping

Trying to put the Result set Values inside a Map


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.


Solution

  • You are putting the same LinkedHashMap instance (referenced by the rowData variable) multiple times in your outer Map. That's the reason the values of the final DB row overwrite all the previous values.

    You have to create a new LinkedHashMap instance for each iteration of the while loop:

    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);
    }