通常在MySQL數據庫的備份和恢復的時候,多是采用在cmd中執行mysql命令來實現。
例如:
mysqldump -h127.0.0.1 -uroot -p123456 test > d:/test.sql ---備份test數據庫到 D 盤
mysql -h127.0.0.1 -uroot -p123456 test< test.sql ---將D備份的數據庫腳本,恢復到數據庫中(數據庫要存在!)
在cmd調用命令行,其實是調用 mysql安裝路徑下面的bin目錄下面的 msqldump.exe和mysql.exe來完成相應的工作
所以,在java代碼中,我們也需要通過調用 mysqldump.exe和mysql.exe來完成備份和恢復的工作
Runtime.getRuntime().exec(String args); java調用外部軟件exe執行命令的api;
linux下:
String[] command = { "/bin/sh", "-c", command };
Process ps = Runtime.getRuntime().exec(command );
windows下:
String[] command = { "cmd", "/c", command};
Process ps = Runtime.getRuntime().exec(command );
RunTime.getRuntime().exec()運行腳本命令的介紹
- 數據庫備份具體代碼
package com.cxx.backupdb; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; /** * @Author: cxx * 數據庫備份與還原 * @Date: 2018/4/28 19:56 */ public class DbOperate { /** * 備份數據庫db * @param root * @param pwd * @param dbName * @param backPath * @param backName */ public static void dbBackUp(String root,String pwd,String dbName,String backPath,String backName) throws Exception { String pathSql = backPath+backName; File fileSql = new File(pathSql); //創建備份sql文件 if (!fileSql.exists()){ fileSql.createNewFile(); } //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql StringBuffer sb = new StringBuffer(); sb.append("mysqldump"); sb.append(" -h127.0.0.1"); sb.append(" -u"+root); sb.append(" -p"+pwd); sb.append(" "+dbName+" >"); sb.append(pathSql); System.out.println("cmd命令為:"+sb.toString()); Runtime runtime = Runtime.getRuntime(); System.out.println("開始備份:"+dbName); Process process = runtime.exec("cmd /c"+sb.toString()); System.out.println("備份成功!"); } /** * 恢復數據庫 * @param root * @param pwd * @param dbName * @param filePath * mysql -hlocalhost -uroot -p123456 db < /home/back.sql */ public static void dbRestore(String root,String pwd,String dbName,String filePath){ StringBuilder sb = new StringBuilder(); sb.append("mysql"); sb.append(" -h127.0.0.1"); sb.append(" -u"+root); sb.append(" -p"+pwd); sb.append(" "+dbName+" <"); sb.append(filePath); System.out.println("cmd命令為:"+sb.toString()); Runtime runtime = Runtime.getRuntime(); System.out.println("開始還原數據"); try { Process process = runtime.exec("cmd /c"+sb.toString()); InputStream is = process.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(is,"utf8")); String line = null; while ((line=bf.readLine())!=null){ System.out.println(line); } is.close(); bf.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("還原成功!"); } public static void main(String[] args) throws Exception { String backName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())+".sql"; DbOperate.dbBackUp("root","123456","ks","F:/",backName); dbRestore("root","123456","db","F://2018-04-30-19-28-28.sql"); } }