我想知道如何从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
答案 0 :(得分:3)
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);
}
}
答案 1 :(得分:2)
mysql -u root -p 123 -h hostname club < dumpfile.sql
需要在SO中的命令行执行,而不是在mysql控制台中执行。
编辑:在Java中,您可以调用SO进程来执行此操作或使用某些库进行备份/还原。尝试dbunit为数据库执行此操作。 我使用dbunit和hibernate一起工作正常。
答案 2 :(得分:1)
在Linux中的shell提示符下,以下内容创建转储:
mysqldump --add-drop-table -u<username> -p<password> <databasename> > dumpfile.sql
同样在shell提示符下,以下内容将dumpfile导入现有数据库:
mysql -u<username> -p<password> <databasename> < dumpfile.sql
答案 3 :(得分:0)
try {
Runtime.getRuntime().exec("/C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump -uroot -p123456 computer -r D:\\zerso\\backup.sql");
JOptionPane.showMessageDialog(null, " make back up");
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, " not back up");
} catch (Exception e) {
System.out.println("Exception");
e.printStackTrace();