简体   繁体   中英

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. My java code is :-

 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. Please help me solve this dilemma.

I believe on windows you have to call the command this way:

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

Also I think it is better to use Runtime.getRuntime().exec(String[]) method

    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

    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();
    //...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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