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

时间:2023-03-08 22:43:22

下班了,利用闲暇时间总结一下如何使用Java语言实现MySQL数据库备份:

  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStreamWriter;
  7. import java.io.PrintWriter;
  8. /**
  9. * MySQL数据库备份
  10. *
  11. * @author GaoHuanjie
  12. */
  13. public class MySQLDatabaseBackup {
  14. /**
  15. * Java代码实现MySQL数据库导出
  16. *
  17. * @author GaoHuanjie
  18. * @param hostIP MySQL数据库所在服务器地址IP
  19. * @param userName 进入数据库所需要的用户名
  20. * @param password 进入数据库所需要的密码
  21. * @param savePath 数据库导出文件保存路径
  22. * @param fileName 数据库导出文件文件名
  23. * @param databaseName 要导出的数据库名
  24. * @return 返回true表示导出成功,否则返回false。
  25. */
  26. public static boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) throws InterruptedException {
  27. File saveFile = new File(savePath);
  28. if (!saveFile.exists()) {// 如果目录不存在
  29. saveFile.mkdirs();// 创建文件夹
  30. }
  31. if(!savePath.endsWith(File.separator)){
  32. savePath = savePath + File.separator;
  33. }
  34. PrintWriter printWriter = null;
  35. BufferedReader bufferedReader = null;
  36. try {
  37. printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
  38. Process process = Runtime.getRuntime().exec(" mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName);
  39. InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
  40. bufferedReader = new BufferedReader(inputStreamReader);
  41. String line;
  42. while((line = bufferedReader.readLine())!= null){
  43. printWriter.println(line);
  44. }
  45. printWriter.flush();
  46. if(process.waitFor() == 0){//0 表示线程正常终止。
  47. return true;
  48. }
  49. }catch (IOException e) {
  50. e.printStackTrace();
  51. } finally {
  52. try {
  53. if (bufferedReader != null) {
  54. bufferedReader.close();
  55. }
  56. if (printWriter != null) {
  57. printWriter.close();
  58. }
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. return false;
  64. }
  65. public static void main(String[] args){
  66. try {
  67. if (exportDatabaseTool("172.16.0.127", "root", "123456", "D:/backupDatabase", "2014-10-14.sql", "test")) {
  68. System.out.println("数据库成功备份!!!");
  69. } else {
  70. System.out.println("数据库备份失败!!!");
  71. }
  72. } catch (InterruptedException e) {
  73. e.printStackTrace();
  74. }
  75. }
  76. }