Codxplore.com

Latest news:

Sahih al-Bukhari (সহীহ বুখারী) is a free Hadith application for android. This application is advertisement free. Download now https://play.google.com/store/apps/details?id=com.akramhossin.bukharisharif

how to export mysql data to csv in java


how to export mysql data to csv in java

In this article i will explain how to export MySQL table data to csv file. To export data to csv at first we need to connect our application to MySQL.

You can follow this tutorial  to learn How to connect to MySQL database in java.

We need to follow these steps in order to export data to csv.

  • Connect to MySQL.
  • Use FileWriter Class.
  • Get Data from MySQL table.
  • Append data to csv file
  • Flash the data
  • Close the writer after successfully write all the data to csv file.

Below is the example of export table data to csv in java.

DB db = new DB();

DB class contains database connection code, we initialize the DB connection before executing the export code.

try {
      FileWriter writer = new FileWriter("C:UsersPublicCompanyList.csv");

      //FileWriter require export file path, in this path generated file will be saved for use.


      String sql = "SELECT companyId,companyName,companyAddress,companyPhone,companyMobile,companyEmail FROM tbl_address_list  ";
      db.rs = db.st.executeQuery(sql);
      db.rs = db.st.getResultSet();
      db.md = db.rs.getMetaData();
      int columnCount = db.md.getColumnCount();
      while (db.rs.next()) {
             for (int i = 1; i <= columnCount; i++) {
                        writer.append(db.rs.getString(i)+',');
              }
              writer.append(' ');
       }
       writer.flush();
       writer.close();               
       JOptionPane.showMessageDialog(rootPane, "Csv file is generated successfully and save into C:UsersPublic");

} catch (Exception io) {
      System.err.println(io);
}

Tags : Java, MySQL,

Views : 1121

Subscribe Us


Follow Us