Reputation: 3166
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]
]
Upvotes: 2
Views: 27254
Reputation: 1
ResultSet resultset = statement.executeQuery(sql);//from DB
int numcols = resultset.getMetaData().getColumnCount();
List <List <String> > result = new ArrayList<>();
while (resultset.next()) {
List <String> row = new ArrayList<>(numcols); // new list per row
for (int i=1; i<= numcols; i++) { // don't skip the last column, use <=
row.add(resultset.getString(i));
System.out.print(resultset.getString(i) + "\t");
}
result.add(row); // add it to the result
System.out.print("\n");
}
Upvotes: 0
Reputation: 37823
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
}
Upvotes: 7