The following is a quick and dirty way to turn a ResultSet in CSV. WARNING: only use it where you're certain that the values in the ResultSet won't break CSV formatting ( you do realise that a good programmer is never 'certain' of input don't you ;) ) otherwise adapt it to use a proper CSV writer such as Ostermiller CSVWriter or something from OpenCSV. The source code is HERE

import java.io.IOException;
import java.io.Writer;

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


public class ResultSetCsvFormatter {
    public static int[] resultSetToCsv(ResultSet rs, Writer out) {
        // Be informative! Return the row & column count in that order in an array
        int[] result = { 00 };

        try {
            // Ensure line separator correct for our platform
            final String LINEFEED = System.getProperty("line.separator");
            ResultSetMetaData metaData = rs.getMetaData();
            int numberOfColumns = metaData.getColumnCount();
            result[1] = numberOfColumns;

            // Get the column names
            String sep = "";

            for (int column = 0; column < numberOfColumns; column++) {
                System.out.print(sep);
                System.out.print(metaData.getColumnLabel(column + 1));
                sep = ",";
            }

            out.write(LINEFEED);

            // Get all rows.
            while (rs.next()) {
                sep = "";

                for (int i = 1; i <= numberOfColumns; i++) {
                    System.out.print(sep);
                    System.out.print("" + rs.getObject(i));
                    sep = ",";
                }

                out.write(LINEFEED);
                // Increment row count
                result[0]++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) { /* ignore */
            }
        }

        return result;
    }
}