Klaus Joe Christiansen Klaus Joe Christiansen - 1 month ago 19x
Java Question

Resultset into 2d array

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()];
sqlresult[i] = result.getArray(sql);

But this i keep getting an error, and its only 1d array.


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 );