我尝试使用以下代码备份mysql数据库。
public boolean backupDB() {
String executeCmd = "mysqldump -u root -p 1234 --add-drop-database -B test -r D:\\backup\\aaa.sql";
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully");
return true;
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
但它总是给我这个错误:
CreateProcess error=2, The system cannot find the file specified
我该如何解决这个问题? 感谢
答案 0 :(得分:1)
修改PATH
外部变量以包含mysqldump.exe
的路径或使用文件的绝对路径。
set PATH=%PATH%;%MYSQL_HOME%\bin
其中MYSQL_HOME
是一个包含MySQL服务器安装文件夹路径的变量。
使用绝对路径时。请注意,此路径取决于您的comp,不应在生产代码中使用。
String executeCmd = "C:\\Programs Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump.exe -u root -p 1234 --add-drop-database -B test -r D:\\backup\\aaa.sql";
答案 1 :(得分:0)
在使用mysqldump之前,请指定其路径:
String executeCmd = "\""+mysqldump_path+"bin\\mysqldump.exe\" --host=localhost --port=3306 --user=root --password=pass database > \""+path+"\"";
runtimeProcess = Runtime.getRuntime().exec(new String[]{"cmd.exe","/c",executeCmd});
int processComplete = runtimeProcess.waitFor();
System.out.println(processComplete);
if(processComplete == 0) {
JOptionPane.showMessageDialog(null, "Backup Created Successfully !");
System.out.println("Backup Created Successfully !");
}
else{
System.out.println("Couldn't Create the backup !");
JOptionPane.showMessageDialog(null, "Couldn't Create the backup !");
}
如果它创建错误并且异常,那么这可以添加一段代码以查看错误:
InputStream errorStream = runtimeProcess.getErrorStream();
byte[] buffer = new byte[errorStream.available()];
errorStream.read(buffer);
String str = new String(buffer);
System.out.println(str);