gpt4 book ai didi

java - 如何使用java备份和恢复mysql数据库

转载 作者:行者123 更新时间:2023-11-29 01:12:02 24 4
gpt4 key购买 nike

我有一个小应用程序,我将用它来备份和恢复一个 mysql 数据库,备份代码如下并且它工作正常,

....
String command = "mysqldump --host=" + dataBase.getHost() + " --user=" + dataBase.getUserName() + " --password=" + dataBase.getPassword() + " "
+ dataBase.getDatabaseName() + " -r " + dataBase.getBackupPath() + "/ofm_mnu_backup_" + bkDate + ".sql";
System.out.println(command);
Process p = null;
try {


Runtime runtime = Runtime.getRuntime();
p = runtime.exec(command);

int processComplete = p.waitFor();

if (processComplete == 0) {

System.out.println("Backup created successfully");

} else {
System.out.println("Could not create the backup");
}
....

但是当我尝试使用以下代码恢复数据库时它不起作用,请帮忙

  ........
String command = "mysqldump --host=" + dataBase.getHost() + " --user="+dataBase.getUserName() + " --password= " + dataBase.getPassword()+""+dataBase.getDatabaseName() + " " + dataBase.getBackupPath();
Process p = null;

try {
System.out.println(command);
Runtime runtime = Runtime.getRuntime();
p = runtime.exec(command);
int processComplete = p.waitFor();

if (processComplete == 0) {
System.out.println("Backup restored successfully");

} else {
System.out.println("Could not restore the backup");
}
......

经过这么多谷歌搜索,我找到了我的问题的答案,

  ......
String[] executeCmd = new String[]{"mysql", [database], "--user=" + [username],"--password=" + [password], "-e", " source " + [absolute path to the sql file]};
p = Runtime.getRuntime().exec(executeCmd);
int processComplete = p.waitFor();
......

在上面的代码中最重要的是**“source”+ [sql文件的绝对路径] **'source'单词和文件路径之间不应该有逗号。

这对我有用,我希望它对你们也有用。

最佳答案

我认为您没有使用 mysqldump命令很正确。你不应该使用 <>字符来表示备份/恢复?对此进行了详细讨论 here .像这样备份:

String command = "mysqldump --host=" + dataBase.getHost() + " --user=" + dataBase.getUserName() + " --password=" + dataBase.getPassword() + " "
+ dataBase.getDatabaseName() + " > " + dataBase.getBackupPath() + "/ofm_mnu_backup_" + bkDate + ".sql";

并恢复:

String command = "mysqldump --host=" + dataBase.getHost() + " --user=" + dataBase.getUserName() + " --password=" + dataBase.getPassword() + " "
+ dataBase.getDatabaseName() + " < " + dataBase.getBackupPath() + "/ofm_mnu_backup_" + bkDate + ".sql";

关于java - 如何使用java备份和恢复mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8470760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com