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();
        }
    }
}

You have records in the table?

yes, i have.

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.

Hi Jordi
Please don't hijack old threads - start a new thread for your question
JC

thanks u so much its really helpfull for me

i want to know, what a function of append? for make a enter in file or make a new column in file? and number in getString for what?
thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.