I'm using a ResultSet in Java, and am not sure how to properly close it. I'm considering using the ResultSet to construct a HashMap and then closing the ResultSet after that. Is this HashMap technique efficient, or are there more efficient ways of handling this situation? I need both keys and values, so using a HashMap seemed like a logical choice.
If using a HashMap is the most efficient method, how do I construct and use the HashMap in my code?
Here's what I've tried:
public HashMap resultSetToHashMap(ResultSet rs) throws SQLException { ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); HashMap row = new HashMap(); while (rs.next()) { for (int i = 1; i <= columns; i++) { row.put(md.getColumnName(i), rs.getObject(i)); } } return row; }
The ResultSet interface declares getter methods (for example, getBoolean and getLong ) for retrieving column values from the current row. You can retrieve values using either the index number of the column or the alias or name of the column.
The ResultSet interface provides getter methods ( getBoolean , getLong , and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient.
Done
EDIT: now that you have posted code, I have made a few changes to it.
public List resultSetToArrayList(ResultSet rs) throws SQLException{ ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); ArrayList list = new ArrayList(50); while (rs.next()){ HashMap row = new HashMap(columns); for(int i=1; i<=columns; ++i){ row.put(md.getColumnName(i),rs.getObject(i)); } list.add(row); } return list; }
I just cleaned up RHT's answer to eliminate some warnings and thought I would share. Eclipse did most of the work:
public List<HashMap<String,Object>> convertResultSetToList(ResultSet rs) throws SQLException { ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>(); while (rs.next()) { HashMap<String,Object> row = new HashMap<String, Object>(columns); for(int i=1; i<=columns; ++i) { row.put(md.getColumnName(i),rs.getObject(i)); } list.add(row); } return list; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With