Reputation: 527
In Java, I have a query like this. In SQL, I can receive 200 records using below query
String sql = Select * from table1
Let say there are 20 columns in above table. I want to loop through the ResultSet and generate the records to the csv file. But the result I got is all the records are displayed in one row. The data don't know when to write a new records to a new row.
Here is what I have so far:
PreparedStatement statment = conn.prepareStatement(sql);
ResultSet result = statment.executeQuery();
ResultSetMetaData meta = resultSet.getMetaData();
int columnCount = meta.getColumnCount();
try (FileWriter out = new FileWriter(path);
CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader(resultSet))) {
while(resultSet.next()) {
for(int i = 1; i<=columnCount; i++{
printer.print(resultSet.getString(i));
}
}
}
Upvotes: 0
Views: 773
Reputation: 3691
You write that each record of each result should be print to the csv file.
But you never call println
at the end of each result on the CSV.
public void print(Object value) throws IOException
Prints the string as the next value on the line.
and
public void println() throws IOException
Outputs the record separator.
while(resultSet.next()) {
for(int i = 1; i<=columnCount; i++{
printer.print(resultSet.getString(i));
}
printer.println();
}
Upvotes: 1