简体   繁体   English

无法将数据从数据库导出到csv文件

[英]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. 我正在尝试从云上的数据库中收集数据,并将每个属性和元组导出到csv文件中。

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"; 我收到错误java.io.FileNotFoundException:c:\\ users \\ myjbdcfile.csv(访问被拒绝)我也尝试过String filename =“c:\\ users \\ myjdbcfile.csv”;

Usually C:/Users will not have permissions to write, unless you modify the permissions. 通常C:/ Users将无权编写,除非您修改权限。 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. 使用StringBuilder和List并围绕它构建逻辑。

Have you consider approach without writing a java code at all? 您是否考虑过不编写Java代码的方法? With IntelliJ IDEA Ultimate you can simply export sql results into a file : 使用IntelliJ IDEA Ultimate,您只需将sql结果导出文件中

在此输入图像描述

of CSV or any custom format you want by creating a custom extractor script . 您可以通过创建自定义提取程序脚本创建 CSV或任何自定义格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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