我有一個SQL腳本,我想從一個運行在Windows上的Java類執行。目前我正在試圖在下面的函數來做到這一點使用ProcessBuilder
:如何使用ProcessBuilder運行MySQL腳本?
public static boolean runSqlScript(String filename, String user, String password) {
ProcessBuilder pb = new ProcessBuilder("mysql", "-u"+user, "-p"+password, "< "+ filename);
try {
Process pr = pb.start();
BufferedReader errors = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
BufferedReader output = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while (pr.isAlive()) {
try {
System.err.println(errors.readLine());
System.out.println(output.readLine());
Thread.sleep(10);
} catch (InterruptedException e) {
break;
}
}
System.err.println(errors.readLine());
System.out.println(output.readLine());
int status = pr.exitValue();
return (status == 0);
} catch (IOException e) {
System.err.println("Error running command: " + e.getMessage());
return false;
}
}
的文件名是腳本的絕對路徑,以及用戶名和密碼驗證正確。但是,當我運行它,我得到的錯誤:
ERROR 1102 (42000): Incorrect database name '< c:/path/to/script.sql'
爲什麼解釋,作爲一個數據庫名稱,而不是一個命令行參數?我可以使用ProcessBuilder來運行這樣的腳本嗎?
嘗試使用空格字符「-u」+ user,而不是「-u」+ user ... – andrii
沒有區別,MySQL不關心用戶名(只是密碼)的空格:https:// dev。 mysql.com/doc/refman/5.5/en/command-line-options.html「對於需要值的簡短選項,選項值可以緊跟在選項字母之後,或者可以在」 – whrrgarbl