Efficient way to Handle ResultSet in Java
- Iterate over the ResultSet
- Create a new Object for each row, to store the fields you need
- Add this new object to ArrayList or Hashmap or whatever you fancy
- Close the ResultSet, Statement and the DB connection
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;}