ResultSet to nested List PDF Print E-mail
Written by Charles   
Monday, 15 December 2008 17:07

Sometimes you want to hold a ResultSet in a Collection and keep it as light as possible. Here's a way to do it as a List of List. The source code is HERE

 


    public static List<List<Object>> resultSetToNestedList(ResultSet rs, boolean includeColumnNames) {
        try {
            // To contain all rows.
            List<List<Object>> rows = new ArrayList<List<Object>>();
            ResultSetMetaData metaData = rs.getMetaData();
            int numberOfColumns = metaData.getColumnCount();

            // Include column headers as first row if required
            if (includeColumnNames) {
                List<Object> columnNames = new ArrayList<Object>();

                // Get the column names
                for (int column = 0; column < numberOfColumns; column++) {
                    columnNames.add(metaData.getColumnLabel(column + 1));
                }
                rows.add(columnNames);
            }

            // Get the data
            while (rs.next()) {
                List<Object> newRow = new ArrayList<Object>();

                for (int i = 1; i <= numberOfColumns; i++) {
                    newRow.add(rs.getObject(i));
                }

                rows.add(newRow);
            }
            return rows;
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }
Comments
Search
Only registered users can write comments!

3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

Last Updated ( Wednesday, 11 November 2009 18:40 )