user1197919
user1197919

Reputation: 111

How to backup a mysql db from java using runtime/process classes?

I have a problem with this code:

 try {            
    String cmd = "C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysqldump.exe -uroot -proot foo_db -rC:\\backup.sql";

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd);

 } catch(Exception e) {}

It doesn't get any error, pratically it doesn't DO anything: no backup and no execution of the cmd. Where's the problem?

It's strange, because the cmd-text is correct... i've tried to do it with 'Execute' command in windows and it works, but in java no.

Thanks in advance.

Upvotes: 0

Views: 1667

Answers (2)

Gray
Gray

Reputation: 116828

Your first problem was, as @pcalcao pointed out, that you are not reporting the exception. You really should never do this. At the very least you should do:

} catch(Exception e) {
    e.printStackTrace();
}

java.io.IOException: Cannot run program "C:\Program": CreateProcess error=193, %1 isn't a Win32 valid application

That says that you have a problem with your application path. By default, if exec() is called with a single argument, then it will break the arguments up by spaces. Since you have spaces in your path you need to pass an array of strings to exec(). Something like:

try {            
    String cmd =
        "C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysqldump.exe";
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(new String[] { cmd, "-uroot", "-proot", "foo_db",
        "-rC:\\backup.sql" });
    // wait for it to finish
    proc.waitFor();
} catch(Exception e) {
    e.printStackTrace();
}

The first argument in the string array passed to exec() is then the full path to the command -- this can have spaces. Each of the other array elements is an argument to the command.

Lastly, you will need to wait for the process to finish otherwise it will execute in the background. That's what the waitFor() does.

Upvotes: 3

pcalcao
pcalcao

Reputation: 15965

You need to escape the whitespace with \, exec is trying to execute "C:\Program", from what you've showed in your answer to my previous comment.

NEVER leave a catch clause empty.

Upvotes: 0

Related Questions