Java-Java调用mysqldump进行数据库备份

 1 public ResultData backupDatabase(Integer type) {
 2     // 构建备份sql的文件名
 3     String sqlFileName = "test" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".sql";
 4     PrintWriter printWriter = null;
 5     BufferedReader bufferedReader = null;
 6 
 7     try {
 8       // 查询所需备份的表(备份的具体哪些表由数据库配置)
 9       List<SwBackUpTable> backUpTableList = dataManagerDao.getBackupTables();
10       StringBuilder stringBuilder = new StringBuilder("");
11 
12       // 所需备份的表的拼接字符串
13       for (SwBackUpTable swBackUpTable : backUpTableList) {
14         stringBuilder.append(" ").append(swBackUpTable.getTableName());
15       }
16       String backupTables = stringBuilder.toString();
17 
18       // 构建备份sql文件路径
19       File savePath = new File(backupSqlPath);
20       if (!savePath.exists()) {
21         // 创建文件夹
22         savePath.mkdirs();
23       }
24       String sqlPath = backupSqlPath + "/" + sqlFileName;
25 
26       //导出指定数据库指定表的结构和数据
27       String command = mysqlPath + backupTables;
28       System.out.println("mysql执行指令:" + command);
29       Process process = Runtime.getRuntime().exec(command);
30 
31       printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(sqlPath), "utf8"));
32       InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
33       bufferedReader = new BufferedReader(inputStreamReader);
34 
35       String line;
36       while ((line = bufferedReader.readLine()) != null) {
37         printWriter.println(line);
38       }
39       printWriter.flush();
40 
41       //0 表示线程正常终止。
42       if (process.waitFor() == 0) {
43         System.out.println("备份数据成功");
44       }
45       System.out.println("数据备份路径==>" + sqlPath);
46 
47       // 备份记录
48       BackUpRecords record = new SwBackUpRecords();
49       record.setName(sqlFileName);
50       record.setTables(backupTables);
51       record.setSource(type);
52       record.setPath(sqlPath);
53       record.setBackupTime(new Date());
54       dataManagerDao.insertRecords(record);
55 
56       return ResultData.success("备份成功");
57     } catch (Exception e) {
58       e.printStackTrace();
59       return ResultData.success("备份失败");
60     } finally {
61       //关闭流
62       try {
63         if (bufferedReader != null) {
64           bufferedReader.close();
65         }
66         if (printWriter != null) {
67           printWriter.close();
68         }
69       } catch (IOException e) {
70         e.printStackTrace();
71       }
72     }
73   }

以上代码中,type字段为业务所需,无需关注.

  mysqlPath: /user/local/mysql/mysql-8.0/bin/mysqldump -uroot -proot Test

    Test为数据库名

  backupSqlPath:服务器存放备份sql的文件夹路径(如:/home/date/backupSql)

posted @ 2022-08-15 16:22  静沐丶暖阳  阅读(619)  评论(0编辑  收藏  举报