Output Access DB query data to a csv file using Java

343 views Asked by At

I am able to open the database file and get the query name and the statement. How do I output the query data to a csv? I thought he below exportWriter would do it but it doesn't work.

Database db = Database.open(new File(args[0]));    
    for(Query query : db.getQueries()) {
        System.out.println(query.getName() + ": " + query.toSQLString());
        if query.getName() = "thequerytooutput" {
            BufferedWriter csvOut = new BufferedWriter(new OutputStreamWriter(System.out));
    ExportUtil.exportWriter(db, query.getName(), csvOut, true, null, '"', 
        SimpleExportFilter.INSTANCE);
        }
    }
2

There are 2 answers

5
JeroSquartini On

I think a better option would be to first store your values from the database into a "two dimensional" list of Strings( I'm assuming you know how to do that[if not, tell me and I'll clarify more]). And then use FileWriter to write the array into a CSV file.

This example was taken from stackabuse.com

List<List<String>> rows = Arrays.asList(
    Arrays.asList("Jean", "author", "Java"),
    Arrays.asList("David", "editor", "Python"),
    Arrays.asList("Scott", "editor", "Node.js")
);

FileWriter csvWriter = new FileWriter("new.csv");
csvWriter.append("Name");
csvWriter.append(",");
csvWriter.append("Role");
csvWriter.append(",");
csvWriter.append("Topic");
csvWriter.append("\n");

for (List<String> rowData : rows) {
    csvWriter.append(String.join(",", rowData));
    csvWriter.append("\n");
}

csvWriter.flush();
csvWriter.close();
0
jtahlborn On

ExportUtil does not run queries, it only dumps tables. You need to provide a valid table name as the second parameter. Jackcess does not have the ability to execute sql queries, as noted here.