0

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

        }
    } 
1
  • 1
    Usr println instead of print or add + \n at the end of the String. That's why println is called like this. Commented Dec 3, 2019 at 16:53

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.