Trying to put the values ​​given for the result on the map

I'm trying to put a resultset (DB query values) inside a LinkedHashMap>.

Each iteration of the line. A value becomes redundant when entered 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 gives me a map of only the last row of the result set for all keys in the dbData map.

+3


source to share


2 answers


You put the same instance LinkedHashMap

(referenced by the variable rowData

) multiple times in your outer one Map

. The reason why the values ​​of the last DB row overwrite all previous values.

You need to create a new instance LinkedHashMap

for each iteration of the loop 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);
}

      

+2


source


Simple: you only have one rowData map - which is updated with row data.

You need to create a fresh map for each row!



In other words: your current code creates a map, one , which is updated for each iteration of the "rows". And in the end, you put the same card in your external card.

0


source







All Articles