Java實現MySQLDatabase Backup
利用閑暇時間總結一下如何使用Java語言實現MySQLDatabase Backup:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
/**
* MySQLDatabase Backup
*
* @author GaoHuanjie
*/
public class MySQLDatabaseBackup {
/**
* Java代碼實現MySQL資料庫匯出
*
* @author GaoHuanjie
* @param hostIP MySQL資料庫所在伺服器位址IP
* @param userName 進入資料庫所需要的使用者名稱
* @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) throws InterruptedException {
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 如果目錄不存在
saveFile.mkdirs();// 建立檔案夾
}
if(!savePath.endsWith(File.separator)){
savePath = savePath + File.separator;
}
PrintWriter printWriter = null;
BufferedReader bufferedReader = null;
try {
printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
Process process = Runtime.getRuntime().exec(" mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName);
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
bufferedReader = new BufferedReader(inputStreamReader);
String line;
while((line = bufferedReader.readLine())!= null){
printWriter.println(line);
}
printWriter.flush();
if(process.waitFor() == 0){//0 表示線程正常終止。
return true;
}
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (printWriter != null) {
printWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public static void main(String[] args){
try {
if (exportDatabaseTool("172.16.0.127", "root", "123456", "D:/backupDatabase", "2014-10-14.sql", "test")) {
System.out.println("資料庫成功備份!!!");
} else {
System.out.println("Database Backup失敗!!!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
--------------------------------------分割線 --------------------------------------
Ubuntu 14.04下安裝MySQL
《MySQL權威指南(原書第2版)》清晰中文掃描版 PDF
Ubuntu 14.04 LTS 安裝 LNMP Nginx\PHP5 (PHP-FPM)\MySQL
Ubuntu 14.04下搭建MySQL主從伺服器
Ubuntu 12.04 LTS 構建高可用分布式 MySQL 叢集
Ubuntu 12.04下原始碼安裝MySQL5.6以及Python-MySQLdb
MySQL-5.5.38通用二進位安裝
Java代碼實現MySQL資料庫的備份與匯入
--------------------------------------分割線 --------------------------------------
本文永久更新連結地址: