Java ResultSet to String toString2dArray(ResultSet resultSet)

Here you can find the source of toString2dArray(ResultSet resultSet)

Description

to Stringd Array

License

Apache License

Declaration

public static String[][] toString2dArray(ResultSet resultSet) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class Main {
    public static String[][] toString2dArray(ResultSet resultSet) {
        /* Method based on http://stackoverflow.com/q/20021139/3626537 */
        String[][] resultArray;/*  ww w  .  j  av  a2 s .c  om*/
        int rowSize = 0;
        int columnSize = 0;

        try {
            resultSet.last();
            rowSize = resultSet.getRow();
            resultSet.beforeFirst();
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            columnSize = resultSetMetaData.getColumnCount();
        } catch (SQLException exc) {
            exc.printStackTrace();
        }

        resultArray = new String[rowSize][columnSize];
        /*
         * SQL rows & columns are 1-indexed while Java arrays are 0-indexed,
         * hence the need for the +1 and -1 manipulations of indexes in this loop.
         */
        int row = 1;
        try {
            while (resultSet.next()) {
                for (int col = 1; col < columnSize + 1; col++) {
                    resultArray[row - 1][col - 1] = resultSet.getString(col);
                }
                row++;
            }
        } catch (SQLException exc) {
            exc.printStackTrace();
        }
        return resultArray;
    }
}

Related

  1. toString(ResultSet rs)