简体   繁体   中英

Can't export data from a database to a csv file

I'm trying to gather data off a database on the cloud and export every attribute and tuple onto a csv file.

static final String JBDC_DRIVER="com.mysql.jbdc.Driver";

public static void main(String[]args){
    String filename = "c:/users/myjbdcfile.csv";

    try{
        FileWriter fw = new FileWriter(filename);
        Connection conn = (Connection) DriverManager.getConnection(DB_URL,user,pass);
        String query  = "select * from allSavedSongs";
        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.flush();
        fw.close();
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

I'm getting the error java.io.FileNotFoundException: c:\\users\\myjbdcfile.csv (Access is denied) I also tried doing String filename = "c:\\users\\myjdbcfile.csv";

Usually C:/Users will not have permissions to write, unless you modify the permissions. I would prefer not to modify the permissions and use different drive or folder.

       String filename = "D:/users/myjbdcfile.csv";
        File dbFile = new File(filename);
        dbFile.getParentFile().mkdirs();
        dbFile.createNewFile();
        FileWriter fw = new FileWriter(dbFile);

Also you are writing the data to file for each record which will impact the performance. Use StringBuilder and List and build the logic around it.

Have you consider approach without writing a java code at all? With IntelliJ IDEA Ultimate you can simply export sql results into a file :

在此输入图像描述

of CSV or any custom format you want by creating a custom extractor script .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM