Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. package com.key.common.plugs.data.mysql;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5.  
  6. /**
  7. * MySQL数据库备份
  8. *
  9. * @author GaoHuanjie
  10. */
  11. public class MySQLDatabaseBackup {
  12.  
  13. /**
  14. * Java代码实现MySQL数据库导出
  15. *
  16. * @author GaoHuanjie
  17. * @param hostIP MySQL数据库所在服务器地址IP
  18. * @param userName 进入数据库所需要的用户名
  19. * @param password 进入数据库所需要的密码
  20. * @param savePath 数据库导出文件保存路径
  21. * @param fileName 数据库导出文件文件名
  22. * @param databaseName 要导出的数据库名
  23. * @return 返回true表示导出成功,否则返回false。
  24. */
  25. public static boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) {
  26. File saveFile = new File(savePath);
  27. if (!saveFile.exists()) {// 如果目录不存在
  28. saveFile.mkdirs();// 创建文件夹
  29. }
  30. if (!savePath.endsWith(File.separator)) {
  31. savePath = savePath + File.separator;
  32. }
  33.  
  34. StringBuilder stringBuilder = new StringBuilder();
  35. stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(hostIP);
  36. stringBuilder.append(" --user=").append(userName) .append(" --password=").append(password).append(" --lock-all-tables=true");
  37. stringBuilder.append(" --result-file=").append(savePath + fileName).append(" --default-character-set=utf8 ").append(databaseName);
  38. try {
  39. Process process = Runtime.getRuntime().exec(stringBuilder.toString());
  40. if (process.waitFor() == 0) {// 0 表示线程正常终止。
  41. return true;
  42. }
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. } catch (InterruptedException e) {
  46. e.printStackTrace();
  47. }
  48. return false;
  49. }
  50.  
  51. public static void main(String[] args) throws InterruptedException {
  52. if (exportDatabaseTool("localhost", "root", "", "/Users/keyuan/Documents/", "2016.sql", "test")) {
  53. System.out.println("数据库备份成功!!!");
  54. } else {
  55. System.out.println("数据库备份失败!!!");
  56. }
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement