Reputation: 47
I just did a mysql query, which was put into a resultset called result.
Now i want it to go into a 2d object, which i can use to show the query result later on.
I am not quite sure how to do it, if i should make a while loop and then put into an array. I have tested that there is something in the result by out.write it to a txt file.
ResultSet result = stmt.executeQuery(sql);
Here is what i got, i tried:
int i =0;
sqlresult = new String[result.getMetaData().getColumnCount()];
while(result.next()){
sqlresult[i] = result.getArray(sql);
i++;
}
But this i keep getting an error, and its only 1d array.
Upvotes: 2
Views: 13455
Reputation: 1
You can do it in simple way as:
ResultSetMetaData metadata = Result.getMetaData();
numberOfColumns = metadata.getColumnCount();
ResultSetArray= new String[numberOfRows][numberOfColumns];
int i=0;
while (Result.next()) {
for (int j = 0; j < numberOfColumns; j++) {
ResultSetArray[i][j] = Result.getString(j+1);
}
i++;
}
Upvotes: 0
Reputation: 31290
This should give you a 2-dimensional data structure, as a List, containing as many elements as there are rows in the result set, with String values for each column value in the row.
int nCol = result.getMetaData().getColumnCount();
List<String[]> table = new ArrayList<>();
while( result.next()) {
String[] row = new String[nCol];
for( int iCol = 1; iCol <= nCol; iCol++ ){
Object obj = result.getObject( iCol );
row[iCol-1] = (obj == null) ?null:obj.toString();
}
table.add( row );
}
// print result
for( String[] row: table ){
for( String s: row ){
System.out.print( " " + s );
}
System.out.println();
}
Upvotes: 11
Reputation: 447
This converts the whole resultset into a 2d array of Objects.
Object[][] resultSet = new Object[rows][columns];
int row = 0;
while (result.next()) {
for (int i = 0; i < columns; i++) {
resultSet[row][i] = result.getObject(i+1);
}
row++;
}
Upvotes: 2
Reputation: 8946
I am not sure what you want but this code will get the column value from the current resultset and store it in an array.
while(result.next()){
java.sql.Array columnVar = rs.getArray("ColumnName");
String[] zips = (String[])columnVar.getArray();
}
Upvotes: 3