博客《Java實現MySQL數據庫備份(一)》使用I/O流的方式實現了MySQL數據庫的備份,這種方法比較繁雜,下面介紹另一種備份MySQL數據庫的方法:
import java.io.File;
import java.io.IOException;
/**
* MySQL數據庫備份
*
* @author GaoHuanjie
*/
public class MySQLDatabaseBackup {
/**
* Java代碼實現MySQL數據庫導出
*
* @author GaoHuanjie
* @param hostIP MySQL數據庫所在服務器地址IP
* @param userName 進入數據庫所需要的用戶名
* @param password 進入數據庫所需要的密碼
* @param savePath 數據庫導出文件保存路徑
* @param fileName 數據庫導出文件文件名
* @param databaseName 要導出的數據庫名
* @return 返回true表示導出成功,否則返回false。
*/
public static boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) {
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 如果目錄不存在
saveFile.mkdirs();// 創建文件夾
}
if (!savePath.endsWith(File.separator)) {
savePath = savePath + File.separator;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(hostIP);
stringBuilder.append(" --user=").append(userName) .append(" --password=").append(password).append(" --lock-all-tables=true");
stringBuilder.append(" --result-file=").append(savePath + fileName).append(" --default-character-set=utf8 ").append(databaseName);
try {
Process process = Runtime.getRuntime().exec(stringBuilder.toString());
if (process.waitFor() == 0) {// 0 表示線程正常終止。
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws InterruptedException {
if (exportDatabaseTool("172.16.0.127", "root", "123456", "D:/backupDatabase", "2014-10-14.sql", "test")) {
System.out.println("數據庫備份成功!!!");
} else {
System.out.println("數據庫備份失敗!!!");
}
}
}