Vikas J
Vikas J

Reputation: 887

Java How to add new empty column to downloaded CSV

I am using Java OpenCSV code to read data from one of the tables of MYSQL and writing resultset to CSV.

Now my requirement is I want to add new empty column name in the header of that downloaded csv as the 1st column.

Not sure about how and where I can make this change.

Example, of what I want is attached.Design

Code:

public void dataFetch(Connection conn,String query) {  // query is hardcoded as :  select Name,Address from dbo.Employee
    ResultSet rs = null;
    Statement stmt = null;          

    try {       
        stmt = conn.createStatement();      
        stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        stmt.setFetchSize(Integer.MIN_VALUE);           
        rs = stmt.executeQuery(query); 

        CSVWriter writer = new CSVWriter(new BufferedWriter(new FileWriter(strSource)));    
        ResultSetHelperService service = new ResultSetHelperService(); 
        service.setDateTimeFormat("yyyy-MM-dd HH:mm:ss.SSS"); 
        System.out.println("**** Started writing Data to CSV **** " +  new Date());         

        writer.setResultService(service);
        int lines = writer.writeAll(rs, true, true, false);  
        writer.flush();
        writer.close();
        System.out.println("** OpenCSV -Completed writing the resultSet at " +  new Date() + " Number of lines written to the file " + lines);  

        rs.close();
        stmt.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

Upvotes: 2

Views: 585

Answers (1)

Grantly
Grantly

Reputation: 2556

Can you re-construct the query string once you are inside the dataFetch function?

To add a column at the END (Last column) I would replace the phrase ' FROM ' with a new field definition so that your query string looks like this:

select Name,Address,'' AS NewColumnName from dbo.Employee

Replace ' FROM ' with ','' AS NewColumnName FROM ' - is my suggestion. (I used capitals just for emphasis)

To add a column at the start I would replace the phrase 'SELECT ' with a new field definition so that your query string looks like this:

select '' AS NewColumnName,Name,Address from dbo.Employee

Replace ' SELECT ' with 'SELECT '' AS NewColumnName, ' - is my suggestion. (I used capitals just for emphasis)

Then you effectively have added new column to your SQL output, and it will propagate into your CSV file, with a header for all the columns as it currently creates.

Upvotes: 2

Related Questions