I'm trying to use mysqldump with java to create a dump for my database.
I've done the code but the condition if(processCompleted == 0)
never happens for some reason that I can not understand. And I say this because on the console there is no exception but it always prints
"Error doing dump!"
which leads me to conclude that if(processCompleted == 0)
is never meet.
Can someone please explain me what I'm doing wrong here?
public boolean backupDatabase(String path, String whichServer)
{
String cmd;
Process runtimeProcess;
if(whichServer.equalsIgnoreCase("local"))
{
cmd = "mysqldump -u " + getSourceUsername() + " -p" + getSourceServerPassword()
+ " --add-drop-database -B " + getSourceDatabase() + " -r " + path;
}
else if(whichServer.equalsIgnoreCase("remote"))
{
cmd = "mysqldump -u " + getDestinationUsername() + " -p" + getDestinationServerPassword()
+ " --add-drop-database -B " + getDestinationDatabase() + " -r " + path;
}
else
{
System.out.println("Input server incorrect");
return false;
}
try{
String[] cmdArray = new String[]{"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysqldump.exe", cmd};
System.out.println("Preparing for dump.");
runtimeProcess = Runtime.getRuntime().exec(cmdArray);
int processCompleted = runtimeProcess.waitFor();
if(processCompleted == 0)
{
System.out.println("Dump done!");
return true;
}
else
{
System.out.println("Error doing dump!");
}
} catch(Exception ex)
{
System.out.println("Exception -> " + ex.getMessage());
}
return false;
}
Here's my code using @MadProgrammer suggestion:
public boolean backupDatabase(String path, String whichServer)
{
List<String> args = new ArrayList<String>();
args.add("C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysqldump.exe");
args.add("-u");
args.add(getSourceUsername());
args.add("-p");
args.add(getSourceServerPassword());
args.add("--add-drop-database");
args.add("-B");
args.add(getSourceDatabase());
args.add("-r");
args.add(path);
try{
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectError();
Process p = pb.start();
InputStream is = p.getInputStream();
int in = -1;
while((in = is.read()) != -1)
{
System.out.println((char) in);
}
int proccessCompleted = p.waitFor();
if(proccessCompleted == 0)
{
System.out.println("Dump done!");
return true;
}
else
{
System.out.println("Error doing dump!");
return false;
}
}
catch(IOException | InterruptedException ex)
{
System.out.println("Exception exportDB -> " + ex.getMessage() + "|" + ex.getLocalizedMessage());
}
return false;
}
PS; where you wrote "//? Is this a single command?" -p
is the command for the password and getSourceServerPassword()
is the method to get the password.
Copyright License:
Author:「dazito」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.
Link to:https://stackoverflow.com/questions/19086052/runtime-exec-to-dump-database-using-mysqldump-java