无法从 java 中的 mysql 导出 csv 文件

Not able to export csv file from mysql in java

我需要导出 mysql table 数据以供用户以 CSV 格式下载。

为了实现这一点,我正在尝试 java runtime exec 函数并执行 "mysql -e"。不幸的是,我被困在了一半。我只能将 sql 输出显示到控制台,但无法将其路由到文件。

工作代码

(我可以在eclipse控制台看到记录)

try {
        Process p = Runtime.getRuntime().exec(new String[]
                {


                "mysql","-h","localhost","-u","admin","-pxyz","myDB","-e", "\"select concat(billing_amount,',') as 'Billing Amount,', concat(amount_paid ,',') as 'Amount Paid,' from invoice\""

                }
                );
         BufferedReader in = new BufferedReader(
                 new InputStreamReader(p.getInputStream()));
         String line = null;
         while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        //process.waitFor();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但是当我尝试使用 "> abc.txt " 将数据导出到文件时,文件没有创建,而是我看到了 mySQL --eclipse 控制台中的帮助选项。这里可能有什么问题?

代码无效

try {
        Process p = Runtime.getRuntime().exec(new String[]
                {


                "mysql","-h","localhost","-u","admin","-pxyz","myDB","-e", "\"select concat(billing_amount,',') as 'Billing Amount,', concat(amount_paid ,',') as 'Amount Paid,' from invoice\"", "> abc.txt"

                }
                );
         BufferedReader in = new BufferedReader(
                 new InputStreamReader(p.getInputStream()));
         String line = null;
         while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        //process.waitFor();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I/O 重定向由 shell 处理,而不是由每个程序处理。因此,mysql 不知道如何处理 > abc.txt。执行 shell 并将完整命令作为单个参数传递,这样在 Unix 系统中可以工作:

Process p = Runtime.getRuntime().exec(new String[] {
     "sh", "-c", "mysql -h localhost -u admin -pxyz myDB -e \"select concat(billing_amount,',') as 'Billing Amount,', concat(amount_paid ,',') as 'Amount Paid,' from invoice\" > abc.txt"
});

但更好的选择是使用 ProcessBuilderredirectOutput(File) 方法。