gpt4 book ai didi

java - 我如何从mysql数据库备份和恢复数据

转载 作者:可可西里 更新时间:2023-11-01 09:49:24 24 4
gpt4 key购买 nike

我想知道如何从 mysql 数据库创建备份并恢复它。我想在我的 Java 应用程序中使用它。

mysql> mysql -u root -p 123  -h hostname club <dumpfile.sql;

但它有这个错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql -u root -p mehdi  -h hostname club < dumpfile.sql' at line 1   

最佳答案

import java.io.IOException;  
/**
*
* @author wakam.cha.hanba@gmail.com
*/

public class DatabaseManager {

public static boolean backup(String mysqldumpPath, String backupPath) {
boolean status = false;
String username = "name";
String password = "pword";
String database = "database_name";


String command = "/" + mysqldumpPath + "/mysqldump -u " + username + " -p" + password + " " + database + " -r " + backupPath;
try {
Process runtimeProcess = Runtime.getRuntime().exec(command);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("DatabaseManager.backup: Backup Successfull");
status = true;
} else {
System.out.println("DatabaseManager.backup: Backup Failure!");
}
} catch (IOException ioe) {
System.out.println("Exception IO");
ioe.printStackTrace();
} catch (Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
return status;
}
public static boolean restore(String filePath){
boolean status = false;
String username = "name";
String password = "pword";
String[] command = new String[]{"mysql", "database_name", "-u" + username, "-p" + password, "-e", " source "+filePath };

try {
Process runtimeProcess = Runtime.getRuntime().exec(command);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("DatabaseManager.restore: Restore Successfull");
status = true;
} else {
System.out.println("DatabaseManager.restore: Restore Failure!");
}
} catch (IOException ioe) {
System.out.println("Exception IO");
ioe.printStackTrace();
} catch (Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
return status;
}

//for testing
public static void main(String args[]){
String backupName = "D:/DatabaseBackup/backupHvs.sql";
DatabaseManager.restore(backupName);
}

}

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

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