how to export my table data which is in mysql database to a csv file
I am not getting any error or exception but my csv file is empty after successful running this code.

code what i did:

import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbToCSV {
    public static void main(String[] args) {
        String filename ="Desktop:test.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 testtable";
            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('\n');
               }
            fw.flush();
            fw.close();
            conn.close();
            System.out.println("CSV File is created successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ohh!!!! now it worked. I was giving wrong filepath.

@DAveAmour, Thanks for reply.

This code works awesome, I was trying to do this for over 2 weeks and I couldn't 'till I found your blog, I have just one question, this import doesn't give me the names of the columns, how can I know them? and how can I write them on mi ouputf csv file? Thank you so much.

This question has already been answered. Start a new discussion instead.