我看过很多关于这个问题的文章,我尝试了所有的文章,但仍然无法使用java创建备份。这是我的代码:
public class CreateBackup {
public static void main(String[] args) {
try {
File file = new File("mysqlBackup");
if (!file.isDirectory()) {
file.mkdir();
}
String fileName = "backup_" + new Date().getTime() + ".sql";
String path = file.getAbsolutePath() + "/" + fileName;
String cmd = "/usr/bin/mysqldump -uroot -proot userDb > " + path; //-The root after u is the mysql database user name, and the 123456 followed by - p is the user password. Note that there is no space; dbName fills in the database name that needs to be backed up, and the greater than sign is followed by the generated file path
System.out.println("path " +cmd);
Process runtimeProcess = Runtime.getRuntime().exec(cmd );
int processComplete = runtimeProcess.waitFor();
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
if (processComplete == 0) {
System.out.println("Backup Complete");
} else {
System.out.println("Backup Failure");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
我试着在ubuntu中运行,也试过使用windows,但提到了mysqldump完整路径";C: \Program Files\MySQL\MySQL Server 5.7\bin\mysqldump"。为什么我的代码总是返回备份失败?请帮帮我。提前谢谢。
我通过添加更多行修复了这段代码。在执行时。
File f = new File(file, new Timestamp(System.currentTimeMillis()).getTime() + ".sql");
String path = f.getPath();
String username = "root";
String password = "root";
String dbname = "userDb";
String executeCmd = "/usr/bin/mysqldump -u" + username + " -p" + password
+ " --add-drop-database -B " + dbname + " -r " + path;
Process runtimeProcess;
try {
// System.out.println(executeCmd);//this out put works in mysql shell
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
System.out.println(executeCmd);
// runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete" + processComplete);
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
希望它能帮助别人。。