gpt4 book ai didi

java - 无法在java中从mysql导出csv文件

转载 作者:行者123 更新时间:2023-11-29 23:00:16 26 4
gpt4 key购买 nike

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

为了实现这一点,我正在尝试 java 运行时 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 " 将数据导出到文件时,该文件未创建,而是在 eclipse 控制台中看到 mySQL --help 选项。这里可能出了什么问题?

代码不工作

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

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

关于java - 无法在java中从mysql导出csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28524758/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com