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.

2 Answers2

3

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);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

Simple: you have only one rowData map - that gets updated with row data.

You have to create a fresh map for each row instead!

In other words: your current code creates one map, that gets updated for each "row" iteration. And in the end, you put that same map into your outer map.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • And why? Seriously: a person who wants to deal with databases should be able to write that code within 2 minutes given the explanation. – GhostCat Aug 09 '17 at 07:37
  • Thanks ! It worked. I just declared the rowdata map inside result set loop. So it instantiate every iteration – Keerthivasan S Aug 09 '17 at 07:38