zoukankan      html  css  js  c++  java
  • Java Web 实现Mysql 数据库备份与还原

    前段时间某某删库事故付出的惨重代价告诉我们: 数据备份的必要性是企业数据管理极其重要的一项工作。

    1. Mysql备份与还原命令

    备份命令:

    mysqldump -h127.0.0.1 -uroot -ppwd test > d:/test.sql  #备份数据库test到 D 盘
    

    还原命令:

    mysql -h127.0.0.1 -uroot -ppwd test< test.sql  ---将D备份的数据库脚本,恢复到数据库test中
    

    原理就是:通过cmd命令行,调用 mysql安装路径下面的bin目录下面的 msqldump.exe和mysql.exe来完成相应的工作.

    2. Web项目中的使用

    备份代码:

    @OperLog("备份新增")
    @PreAuthorize("@ps.hasPerm('backup_add')")
    @PostMapping("/save")
    @ResponseBody
    @Transactional
    public R save(@RequestBody Backup backup) {
         String name = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
         backup.setName(name);
         String filePath = profile + "backup/";
         File uploadDir = new File(filePath);
         if (!uploadDir.exists())
              uploadDir.mkdirs();
         String cmd = "cmd /c mysqldump -u" + username + " -p" + password + " " + CommonConstants.DB_NAME + " > "
                    + filePath + CommonConstants.DB_NAME + "_" + name + ".sql";
         backup.setPath(filePath + CommonConstants.DB_NAME + "_" + name + ".sql");
         //执行备份命令
         try {
              StaticLog.info("执行备份命令:" + cmd);
              RuntimeUtil.exec(cmd);
         } catch (Exception ex) {
              return R.error(ex.getMessage());
         }
         backupService.save(backup);
         return R.ok();
    }
    

    还原代码:

    @OperLog("备份还原")
        @PreAuthorize("@ps.hasPerm('backup_restore')")
        @GetMapping("/restore/{id}")
        @ResponseBody
        public R restore(@PathVariable("id") Integer id) {
            Backup backup = backupService.getById(id);
            if (backup != null) {
                String cmd = "cmd /c mysql -u" + username + " -p" + password + " " + CommonConstants.DB_NAME + " < " + backup.getPath();
                //执行还原命令
                try {
                    StaticLog.info("执行还原命令:" + cmd);
                    RuntimeUtil.exec(cmd);
                } catch (Exception ex) {
                    return R.error(ex.getMessage());
                }
           }
           return R.ok();
    }
    

    3. 环境变量Path中添加mysql安装路径

    如:计算机-》属性-》高级系统设置-》环境变量-》系统变量Path-》增加 ;C:\Program Files\MySQL\MySQL Server 5.7\bin;

    既然数据库备份文件都到本地了,当然可以将sql脚本文件通过电子邮件发到你的邮箱,如果再加个定时备份就更完美了

    注:环境变量一定要配置否则无法备份成功,以上代码适用于Windows环境
    代码地址:[代码下载]
  • 相关阅读:
    LeetCode 350. Intersection of Two Arrays II (两个数组的相交之二)
    LeetCode 349. Intersection of Two Arrays (两个数组的相交)
    LeetCode 290. Word Pattern (词语模式)
    LeetCode 266. Palindrome Permutation (回文排列)$
    34.Search for a Range
    spark连接mongodb
    NLPIR中文分词器的使用
    scala和maven整合实践
    Spark中的键值对操作-scala
    301.Remove Invalid Parentheses
  • 原文地址:https://www.cnblogs.com/entfrm/p/12545772.html
Copyright © 2011-2022 走看看