1

I need to download the csv file from database using database.

I have jdbc connection and execute the query , get the data from database.Those values are download as csv format using java class.

Java class:
String filename="Cases.csv";
//here database connection.


ResultSet rst= stmt.executeQuery(qry);
    System.out.println("1"+rst);
    if(rst.next())
    {

    Content=rst.getString("USER_details");

    }
    //ServletOutputStream out = null;
    //out.println(Content);
    System.out.println("1"+Content);
    byte requestBytes[] = Content.getBytes();
    ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);
    response.reset();
    response.setContentType("application/text");
    response.setHeader("Content-disposition","attachment; filename=" +filename);
    byte[] buf = new byte[1024];
    int len;
    while ((len = bis.read(buf)) > 0){
    response.getOutputStream().write(buf, 0, len);
    }
    bis.close();
    response.getOutputStream().flush(); 
    }
    catch(Exception e){
    e.printStackTrace();
    }

How to get all values from database to csv format ?

2
  • I would always do while(rst.next()) instead of if(rst.next()) in case you return multiple rows in the future. Also put your close statments in a finally block. Commented Jul 2, 2010 at 17:56
  • I want to get more than one row and coloumn.How to modify the code ? Commented Jul 2, 2010 at 18:08

1 Answer 1

3

OpenCSV supports exporting a ResultSet to CSV:

CSVWriter writer = ...;
ResultSet rs = ...;
writer.writeAll(rs, true);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.