[英]Not able to export csv file from mysql in java
我要求導出用戶以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的更好選擇是使用ProcessBuilder
和redirectOutput(File)
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.