我正在尝试使用 mysqldump 和 java 为我的数据库创建转储。
我已经完成了代码,但由于if(processCompleted == 0)
某种我无法理解的原因,这种情况从未发生过。我这么说是因为在控制台上没有例外,但它总是打印
“转储出错!”
这使我得出结论,如果(processCompleted == 0)
永远不会满足。
有人可以解释一下我在这里做错了什么吗?
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;
}
这是我使用@MadProgrammer 建议的代码:
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;
}
附言; 你在哪里写“//?这是一个单一的命令吗?” -p
是密码的命令,getSourceServerPassword()
是获取密码的方法。