Reputation: 8717
I have an mySQL ResultSet and I want to store that in my HashMap:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Gets the Result set here then:
while(rs.next()){
rs.put("Column1","Column2");
}
This is not right, could some explain the correct way to do it please?
Upvotes: 4
Views: 36888
Reputation: 191
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
Map map = new HashMap();
for (int i = 1; i <= meta.getColumnCount(); i++) {
String key = meta.getColumnName(i);
String value = rs.getString(key);
map.put(key, value);
}
list.add(map);
}
Upvotes: 19
Reputation: 116828
If I read your question correctly, it would be something like:
Map<String, Integer> myMap = new HashMap<String, Integer>();
...
// parsing the column each time is a linear search
int column1Pos = rs.findColumn("Column1");
int column2Pos = rs.findColumn("Column2");
while (rs.next()) {
String column1 = rs.getString(column1Pos);
int column2 = rs.getInt(column2Pos);
myMap.put(column1, column2);
}
Upvotes: 2
Reputation: 26574
You probably want a Map<YourKeyType, Map<String, Integer>>
.
So you are mapping each row by id (whatever type that is) to a map of column/value. Here I assumed every column was Integer since that's what you had in your question, but you could use Object if they differ. Then you could access the values with myMap.get(myId).get( "column1" );
or walk it using the keySet() or whatever you need to do with it.
To populate the map, you would do something like
Map<KeyType, Map<String, Object>> resultMap = new HashMap<KeyType, Map<String, Object>>();
while( rs.next()) {
Map<String, Object> tmpMap = new HashMap<String, Object>();
tmpMap.put( "Column1", rs.get( "Column1" );
// etc. for other columns
resultMap.put( rs.get( "id" ), tmpMap );
}
Upvotes: 0