如題,由於項目需要,研究並實現了java web的 mysql數據庫的備份、下載、恢復功能,中間遇到一些問題,耗費了不少時間,下面讓我一一道來:
背景介紹:
- window 7系統
- mysql 5.7
- eclipse
- spring mvc
- tomcat 7
- jdk 1.7
先上代碼:
使用mysql的mysqldump 命令進行備份。
/**
* Java代碼實現MySQL數據庫備份
*
* @author lgc
* @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) throws InterruptedException {
boolean fa = false;
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 如果目錄不存在
saveFile.mkdirs();// 創建文件夾
}
if (!savePath.endsWith(File.separator)) {
savePath = savePath + File.separator;
}
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
String backup = "mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " " + databaseName
+ " --set-charset=UTF8 ";
String path = "E:\\";//這裏是你複製的mysqldump.exe所在的文件目錄下
String commad = "cmd /c " + path + backup + ">" + savePath + fileName;
System.out.println(commad);
Runtime.getRuntime().exec(commad);
fa = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.close();
}
}
return fa;
}
恢復備份:
// 數據庫恢復
public static void load(String filename) {
try {
String path = "E:\\";
String commad = "cmd /c " + path+"mysql -u root -pcisoft jeecms ";
Runtime rt = Runtime.getRuntime();
// 調用 mysql 的 cmd:
Process child = rt.exec(commad);
OutputStream out = child.getOutputStream();//控制檯的輸入信息作爲輸出流
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(filename), "utf8"));
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
writer.write(outStr);
// 注:這裏如果用緩衝方式寫入文件的話,會導致中文亂碼,用flush()方法則可以避免
writer.flush();
// 別忘記關閉輸入輸出流
out.close();
br.close();
writer.close();
System.out.println("/* Load OK! */");
} catch (Exception e) {
e.printStackTrace();
}
}
坑一:
- mysql 安裝在c盤默認路徑下,Program Files 文件夾名稱之間有空格,導致程序明明運行一切正常,就是無法導出數據,文件大小始終爲0kb。