Home Tutorial Java Core Export Database table to CSV File

 
 

Share on Google+Share on Google+
Export Database table to CSV File
Posted on: September 19, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to retrieve data from database and save it to CSV File.

Export Database table to CSV File

In this tutorial, you will learn how to retrieve data from database and save it to CSV File.

The Comma-separated values, better knows as CSV is having a delimited data format. It has field/columns separated by the comma and records/rows separated by new lines. It is very similar to text files. Exporting or writing data to csv file is exactly same as writing into a CSV file.

Here is a database table is to be extracted:

Example

import java.io.*;
import java.sql.*;
 
public class DatabaseToCSV { 
public static void main(String[]args){ 
  String filename = "c:\\myjdbcfile.csv";
  try{  
  FileWriter fw = new FileWriter(filename);
    Class.forName("com.mysql.jdbc.Driver").newInstance();
  Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
  String query  = "select * from person";
  Statement stmt = conn.createStatement();
  ResultSet rs = stmt.executeQuery(query);
  while(rs.next())
  {
  fw.append(rs.getString(1));
  fw.append(',');
  fw.append(rs.getString(2));
  fw.append(',');
  fw.append(rs.getString(3));
  fw.append(',');
  fw.append(rs.getString(4));
  fw.append('\n');
  }
  fw.flush();
  fw.close();
  conn.close();
  System.out.println("CSV File is created successfully.");
  } catch (Exception e) {
  e.printStackTrace();
  }
  
  }
}

Description Of Code: In this example, we have created a database connection and fetch the records from the table using ResultSet. We have used FileWriter object to create a CSV file, same as to create a normal text file, and save the fetched data to it. There is no need to use any third party library.

Output: Data is saved to csv file

Advertisement

Related Tags for Export Database table to CSV File:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 19, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com