Export Database table 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.

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

Ads