Friday, 11 April 2014

Efficient way to Handle ResultSet in Java

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

No comments:

Post a Comment