简体   繁体   English

mysqldump在java中不起作用

[英]mysqldump does not work in java

I am using this command line argument to clone a database :- 我正在使用此命令行参数来克隆数据库:-

"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump"  -u root -ppass -d oldDB | mysql -u root -ppass -DnewDB

This piece works fine when directly pasted into command line. 直接粘贴到命令行中时,此代码效果很好。 But, when I tried running this argument using java, it did not work. 但是,当我尝试使用java运行此参数时,它不起作用。 My java code is :- 我的Java代码是:-

 String serverLoc = "C:\\Program Files\\MySQL\\MySQL Server 5.6\\";
 String a = "\"" + serverLoc + "bin\\mysqldump\" " ;
 String cmd = a + "-u root -ppass -d oldDB | mysql -u root -ppass -DnewDB";

 Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
 int processComplete = runtimeProcess.waitFor();

 if (processComplete == 0) {
     System.out.println("SUCCESS");
 } else {
     System.out.println("ERROR");
 }

 //OUTPUT : ERROR

Exception handling not shown as no stack trace is printed. 未显示异常处理,因为未打印堆栈跟踪。 When I print cmd , the above desired string is printed which works when pasted into command line. 当我打印cmd ,将打印上述所需的字符串,该字符串在粘贴到命令行时有效。 Please help me solve this dilemma. 请帮助我解决这个难题。

I believe on windows you have to call the command this way: 我相信在Windows上,您必须以这种方式调用命令:

Runtime.getRuntime().exec("cmd " + ecuteCmd)

Also I think it is better to use Runtime.getRuntime().exec(String[]) method 另外我认为最好使用Runtime.getRuntime().exec(String[])方法

    String prog = "C:\\program files\\server\\xampp\\mysql\\bin\\mysql";
    String user = "-uroot";
    String pass = "-ppass";
    Process runtimeProcess = Runtime.getRuntime().exec(new String[] { prog, user, pass });

The modern way by using ProcessBuilder: thx @Daniel 使用ProcessBuilder的现代方式: thx @Daniel

    String prog = "C:\\program files\\server\\xampp\\mysql\\bin\\mysql";
    String user = "-uroot";
    String pass = "-ppass";

    ProcessBuilder builder = new ProcessBuilder(prog, user, pass);
    Process runtimeProcess = builder.start();
    int result = runtimeProcess.waitFor();
    //...

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

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