/** Copyright (c) 2007 Ricebridge. BSD License. */ package com.ricebridge.example.updown; import java.io.OutputStream; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Properties; import com.ricebridge.csvman.CsvManager; import com.ricebridge.csvman.CsvSaver; import com.ricebridge.csvman.CsvSpec; /** Extract data from database, convert it to CSV, and send the CSV to an * OutputStream. */ public class CsvDownloader extends DownloaderSupport { public void process( OutputStream pOutputStream, Properties pProperties ) throws Exception { mDatabaseErrors = new ArrayList(); // use CSV Manager to create the CSV file CsvSpec csvspec = makeCsvSpec( pProperties ); CsvManager csvman = new CsvManager( csvspec ); CsvSaver csvsvr = csvman.makeSaver( pOutputStream ); // select all database table columns PreparedStatement selectsql = mConnection.prepareStatement( "SELECT * FROM "+mTableName+";" ); ResultSet rs = null; try { rs = selectsql.executeQuery(); Converter conv = new Converter(mTableName,rs); csvsvr.begin(); // the first line is the column names so that uploading will also work csvsvr.next( conv.getColumnNames() ); // get each row and output it as a CSV line while( rs.next() ) { String[] data = conv.getData(rs); csvsvr.next(data); } } catch( Exception e ) { mDatabaseErrors.add(e); } finally { csvsvr.end(); close( rs, selectsql, mConnection ); } } /** The particular CSV format to use is specified by a set of properties. */ public CsvSpec makeCsvSpec( Properties pProperties ) { CsvSpec csvspec = CsvSpecHandler.makeCsvSpec(pProperties); return csvspec; } }