Andrei Vasilev Andrei Vasilev - 5 months ago 94
Java Question

How to convert resultset to csv?

I connect to

Oracle
and get a
ResultSet


ResultSet rs ...


I am trying to convert ResultSet to CSV. I am using
openCSV API


CSVWriter wr = new CSVWriter(new FileWriter("Report.csv"), ',');
wr.writeAll(rs, true);
wr.flush();
wr.close();


however, every time i do this , the data gets appended . But i need for it to get overwritten .
How can i overwrite the file .

Is there any better way ?

Answer

As i mentioned in the comment you can write data directly

puclic static void main (Stirng [] args) {
ResulSet rs = ... // whatever your code is
convertToCsv ( rs ) ;

}



public static void convertToCsv(ResultSet rs) throws SQLException, FileNotFoundException {
        PrintWriter csvWriter = new PrintWriter(new File("whatever.csv")) ;
        ResultSetMetaData meta = rs.getMetaData() ; 
        int numberOfColumns = meta.getColumnCount() ; 
        String dataHeaders = "\"" + meta.getColumnName(1) + "\"" ; 
        for (int i = 2 ; i < numberOfColumns + 1 ; i ++ ) { 
                dataHeaders += ",\"" + meta.getColumnName(i) + "\"" ;
        }
        csvWriter.println(dataHeaders) ;
        while (rs.next()) {
            String row = "\"" + rs.getString(1) + "\""  ; 
            for (int i = 2 ; i < numberOfColumns + 1 ; i ++ ) {
                row += ",\"" + rs.getString(i) + "\"" ;
            }
        csvWriter.println(row) ;
        }
        csvWriter.close();
    }

This will overwrite the file and you will not have to refer to a third party API just for one method