5

I am trying to convert a ResultSet object to a String object in CSV format. I've tried using OpenCV to convert it into CSV file but I need to have it as a string. There is an option to first convert it into a file and then convert the data into a string and then delete the file but that would be an extra overhead which I can't have.

Is there a way to achieve it, I tried searching but haven't anything so far.

HyperioN
  • 3,433
  • 2
  • 22
  • 36
  • why not just right a method to do it? – Alex May 12 '17 at 20:56
  • that would be my last option :) – HyperioN May 12 '17 at 20:59
  • Isn't [OpenCV](http://opencv.org/about.html) a bit of overkill for a CSV formatter? Why not use dedicate CSV library, e.g. [Apache Commons CSV](https://commons.apache.org/proper/commons-csv/) or any of the other libraries you can find by [**searching the web**](https://www.google.com/search?q=java+csv+library)? – Andreas May 12 '17 at 21:02
  • please mention the reason before voting down – HyperioN May 12 '17 at 21:21

2 Answers2

6

Apache Commons CSV

Alternatively, you can use the CSVPrinter from Apache Commons CSV.

CSVPrinter::printRecords( ResultSet )

The method CSVPrinter::printRecords takes a ResultSet argument.

See the key line csvPrinter.printRecords(resultSet); in the following example code.

package org.myorg;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class QueryToCSV {

    public static void main(String[] args) throws IOException  {

        if ( args.length < 2)
            throw new IllegalArgumentException("Usage: QueryToCSV.jar <JDBCConnectionURL> <SQLForQuery> -> output to STDOUT and STDERR");

        // Create a variable for the connection string.
        String connectionUrl = args[0];
        String sqlQuery = args[1];
        try ( Connection conn = DriverManager.getConnection(connectionUrl); ) { 

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

            try (Statement st = conn.createStatement();) {
                ResultSet resultSet = st.executeQuery(sqlQuery);
                CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(resultSet));
                csvPrinter.printRecords(resultSet);
                csvPrinter.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        }
        catch (IllegalArgumentException ie) {
            System.err.println(ie.getMessage());
            System.exit(1);
        }
    }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
beaudet
  • 886
  • 1
  • 10
  • 13
3

Do not write your own method, CSV is not just strings concatenated by commas. There are several pifails regarding quotas, their escaping etc. Use dedicated libraries. Personally I prefer univocity-parsers for "broken" csv files but if you deal with ResultSet you may use opencsv library.

    StringWriter stringWriter = new StringWriter();
    CSVWriter csvWriter = new CSVWriter(stringWriter);
    csvWriter.writeAll(resultSet, true); // including column names
    String result = stringWriter.toString();
Andriy Slobodyanyk
  • 1,965
  • 14
  • 15
  • 3
    Author of the univocity parsers library here: You can write the resultset with a single line of code: `new CsvRoutines().write(resultSet, stringWriter)`. Hope it helps! – Jeronimo Backes May 15 '17 at 04:19
  • @JeronimoBackes thanks for your suggestion. I'm reading the docs, trying to set delimiter using CsvParserSettings settings = new CsvParserSettings();settings.getFormat().setDelimiter('|');csvRoutines.setParserSettings(settings);csvRoutines.write(resultSet, stringWriter); but i'm still getting comma seperated output. – HyperioN May 15 '17 at 06:26
  • Don't bother, I figured it out. Had to use CsvWriterSettings instead of CsvParserSettings. – HyperioN May 15 '17 at 06:48
  • If you just need the Strings you can replace the CSVWriter with a ResultSetHelperService (http://opencsv.sourceforge.net/apidocs/com/opencsv/ResultSetHelperService.html) and call the getColumnValues method with the result set until you get back null or an exception. each call will give you the array of strings representing one row of data. Internally this is what the CSVWriter is calling. – Scott Conway May 15 '17 at 16:55