Aim is to create a groovy script that will read from the database and export to a csv file. I am using the apache commons csv writer. I have been working with this javacode geeks - apache commons tutorial..
This works I have put here to help explain what I am trying to achieve.
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);
//Write a new student object list to the CSV file
for (Student student : students) {
List studentDataRecord = new ArrayList();
studentDataRecord.add(String.valueOf(student.getId()));
studentDataRecord.add(student.getFirstName());
studentDataRecord.add(student.getLastName());
csvFilePrinter.printRecord(studentDataRecord);
}
What Im trying to do In groovy/java.
I have created a groovy script calls the DB ok. I can make it iterate and loop over fine and prints the rows. However I dont want to manually write all the 'student.getFirstName' student.getLastName etc calls. If I modify the query in the future it makes more work -- I just want to export it straight to csv having only modified the query.
Something like this is what I have so far.. I am unsure of the syntax etc.
#!/usr/bin/env groovy
import groovy.sql.Sql
import org.apache.commons.csv.CSVFormat
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);
sql.eachRow("Select field1, field2, field3, etc FROM Student") {
for( keyIndex k ){
List studentDataRecord = new ArrayList();
studentDataRecord.add(k.value)
}
csvFilePrinter.printRecord(studentDataRecord);
}