Search code examples
javadatabaseresultset

Put ResultSet into HashMap?


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?


Solution

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