Java实现MySQL数据库备份(二)

  1. import java.io.File;  
  2. import java.io.IOException;  
  3.   
  4. /** 
  5.  * MySQL数据库备份 
  6.  *  
  7.  * @author GaoHuanjie 
  8.  */  
  9. public class MySQLDatabaseBackup {  
  10.   
  11.     /** 
  12.      * Java代码实现MySQL数据库导出 
  13.      *  
  14.      * @author GaoHuanjie 
  15.      * @param hostIP MySQL数据库所在服务器地址IP 
  16.      * @param userName 进入数据库所需要的用户名 
  17.      * @param password 进入数据库所需要的密码 
  18.      * @param savePath 数据库导出文件保存路径 
  19.      * @param fileName 数据库导出文件文件名 
  20.      * @param databaseName 要导出的数据库名 
  21.      * @return 返回true表示导出成功,否则返回false。 
  22.      */  
  23.     public static boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) {  
  24.         File saveFile = new File(savePath);  
  25.         if (!saveFile.exists()) {// 如果目录不存在  
  26.             saveFile.mkdirs();// 创建文件夹  
  27.         }  
  28.         if (!savePath.endsWith(File.separator)) {  
  29.             savePath = savePath + File.separator;  
  30.         }  
  31.   
  32.         StringBuilder stringBuilder = new StringBuilder();  
  33.         stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(hostIP);  
  34.         stringBuilder.append(" --user=").append(userName) .append(" --password=").append(password).append(" --lock-all-tables=true");  
  35.         stringBuilder.append(" --result-file=").append(savePath + fileName).append(" --default-character-set=utf8 ").append(databaseName);  
  36.         try {  
  37.             Process process = Runtime.getRuntime().exec(stringBuilder.toString());  
  38.             if (process.waitFor() == 0) {// 0 表示线程正常终止。  
  39.                 return true;  
  40.             }  
  41.         } catch (IOException e) {  
  42.             e.printStackTrace();  
  43.         } catch (InterruptedException e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.         return false;  
  47.     }  
  48.   
  49.     public static void main(String[] args) throws InterruptedException {  
  50.         if (exportDatabaseTool("172.16.0.127", "root", "123456", "D:/backupDatabase", "2014-10-14.sql", "test")) {  
  51.             System.out.println("数据库备份成功!!!");  
  52.         } else {  
  53.             System.out.println("数据库备份失败!!!");  
  54.         }  
  55.     }  
  56. }  

猜你喜欢

转载自blog.csdn.net/java_12138/article/details/81065991