Is there a simple Java library or approach that will take a SQL query and output the result to a CSV file?
Update: I found there were a couple other related SO posts existing (1, 2)
I have used opencsv and it has worked well. See the sample on the linked page under "Can I dump out SQL tables to CSV?"
I've found DBUnit quite easy to use. Example taken from http://www.dbunit.org/faq.html#extract - Modified to use CsvDataSetWriter
instead of FlatXmlDataSet
:
public static void main(String[] args) throws Exception
{
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
QueryDataSet partialDataSet = new QueryDataSet(connection);
partialDataSet.addTable("FOO", "SELECT * FROM TABLE WHERE COL='VALUE'");
CsvDataSetWriter.write(partialDataSet, new File("outputDir"));
}