在java里面使用 Java.lang.Runtime 执行系统系统运行环境里面的命令,从而使用mysql自带的备份及恢复工具达到对数据库的备份和恢复
package org.hinsteny.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestBackUpDataBase {
private String pghome = "C:";
private String pghomeString = "C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\";
private String dataBaseUser = "root";
private String dataBasePass = "123456";
private String dataBaseName = "spring";
private String backupSql = "C:\\spring.sql";
/**
* 备份数据库
* @param metaData
* @return
*/
public Boolean backupDataBase(){
StringBuilder command = new StringBuilder();
command.append(pghomeString).append("mysqldump.exe").append(" --default-character-set=utf8").append(" -u")
.append(dataBaseUser).append(" -p").append(dataBasePass).append(" ").append(dataBaseName)
.append(" -B -r ").append(backupSql);
System.out.println(command.toString());
Process p = null;
try {
Runtime runtime = Runtime.getRuntime();
p = runtime.exec(command.toString());
int processComplete = p.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully!");
} else {
System.out.println("Could not create the backup");
}
}catch (IOException exception){
System.out.println("IOException");
}catch (InterruptedException exception){
System.out.println("InterruptedException");
}
return true;
}
/**
* 恢复数据库
* @param metaData
* @return
* @throws IOException
*/
public Boolean restoreDataBase() throws IOException{
StringBuilder command = new StringBuilder();
command.append(pghome).append("\n")
.append("cd ").append(pghomeString).append("\n")
.append("mysql.exe").append(" -u").append(dataBaseUser).append(" -p").append(dataBasePass).append(" ")
.append(dataBaseName).append(" < ").append(backupSql).append("\n")
.append("exit");
System.out.println(command.toString());
File f = new File("restore.bat");
FileOutputStream fos = new FileOutputStream(f);
fos.write(command.toString().getBytes());
fos.close();
Process p = null;
try {
Runtime runtime = Runtime.getRuntime();
p = runtime.exec("cmd /C start restore.bat");
int processComplete = p.waitFor();
if (processComplete == 0) {
System.out.println("Backup restored successfully");
} else {
System.out.println("Could not restore the backup");
}
}catch (IOException exception){
System.out.println("IOException");
}catch (InterruptedException exception){
System.out.println("InterruptedException");
}
return true;
}
public static void main(String[] args) throws IOException {
TestBackUpDataBase tb = new TestBackUpDataBase();
tb.backupDataBase();
tb.restoreDataBase();
}
}