Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 747
Klaus Joe Christiansen Avatar asked Sep 26 '26 06:09

Klaus Joe Christiansen


2 Answers

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();
}
like image 195
laune Avatar answered Sep 27 '26 19:09

laune


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();
        }
like image 38
SparkOn Avatar answered Sep 27 '26 20:09

SparkOn