returning an arraylist of arraylist from a resultset in java

arraylist, java, prepared-statement, resultset, sql

Solution

Like this:

List<List<String>> result = new ArrayList<>();  // List of list, one per row
...
while (resultset.next()) {
    List<String> row = new ArrayList<>(numcols); // new list per row
    int i = 1;
    while (i <= numcols) {  // don't skip the last column, use <=
        row.add(resultset.getString(i++));
    }
    result.add(row); // add it to the result
}

Problem

I created a database wrapper class in java and created a method called `fetchAll(query)`. ``` this.openConnection(); ArrayList<String> results = new ArrayList<String>(); PreparedStatement stmt = this.conn.prepareStatement(query); ResultSet resultset = stmt.executeQuery(); ResultSetMetaData metadata = resultset.getMetaData(); int numcols = metadata.getColumnCount(); while (resultset.next()) { int i = 1; while (i < numcols) { results.add(resultset.getString(i++)); } } this.closeConnection(); return results; ``` Now it returns something like this: ``` [1, name1, address1, age1, 2, name2, address2, age2, 2, name2, address2, age3] ``` Which I found odd and the method does not return all columns, it lacks 1 column, why is it? How can I achieve something like this ``` [ [1,name1,address1,age1,bday1], [2,name2,address2,age2,bday2], [3,name3,address3,age3,bday3] ] ```

Original source