Friday, September 28, 2012

Convert ResultSet to Array in Java

public String[] convertRStoArray(ResultSet resultSet, boolean closeResultSet) {
        String[] arrayofDataColumns = null;
        Map columnsMap = new HashMap();
        int columns = 0;
        try {
            List<String> record = new ArrayList<String>();
            while (resultSet.next()) {
                arrayofDataColumns = new String[resultSet.getMetaData().getColumnCount()];
                columns = (resultSet.getMetaData()).getColumnCount();
                String value = null;
                for (int i = 1; i <= columns; i++) {
                    value = resultSet.getString(i);
                    record.add(value);
                    if (columnsMap.containsKey(i)) {
                        if (value != null && !value.equals("")) {

                            if (columnsMap.get(i) != null && !columnsMap.get(i).equals("") && !columnsMap.get(i).equals(value)) {
                                value = columnsMap.get(i) + "|" + value;
                                columnsMap.put(i, value);
                            }
                        }
                    } else {
                        columnsMap.put(i, value);
                    }
                }
                Object[] keys = columnsMap.keySet().toArray();
                for (int ii = 0; ii < keys.length; ii++) {
                    arrayofDataColumns[ii] = (String) columnsMap.get(ii + 1);
                }
            }

        } catch (Exception e) {
            logger.log(Level.SEVERE, "Got the exception in convertRStoArray:" + e.getMessage());
        } finally {
            if (closeResultSet)
                closeResultSet(resultSet);
        }
        return arrayofDataColumns;
    }