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);
}
}
}