JAVA开启进程实现mysql数据库的自动备份和自动还原

JAVA实现mysql数据库的自动备份和自动还原

在介绍前我要说一下,网上的例子不少,但是坑很多,有些代码看起来是对的,但是小问题不少,原因在于楼主没有测试过,或者没有交代使用时的特殊环境。以下代码都是亲身测试过的。

  1. 项目背景:使用java实现远程备份mysql数据库到本地电脑,并可以将本地数据库的备份还原到远程mysql数据库。本机环境windows。

  2. 注意:本机必须已经装了mysql数据库,并且将mysql 的bin加在了系统环境变量中。我的mysql在c盘,以下代码也是以C盘的mysql的bin下运行的。具体要以你实际安装MYSQL的位置而定,不然就会自己坑自己了。

  3. 代码逻辑:很重要!!!

  4. 我们首先(在远程数据库)创建一个有测试数据的库:robot,一个空的数据库(没表,没数据)robot-test。

  5. 我们第一步将robot数据库备份到本地电脑d:\test,名字命名:robot-test.sql。

  6. 查看本地电脑的d:\test\robot-test.sql是否存在,并确定是否备份成功。

  7. 第二步,将robot-test.sql还原到之前创建的空数据库:robot-test。

  8. 查看robot-test数据库的表和数据是否还原成功。

备份和还原方法写到一个类中:

package com.company;
import java.io.File;
import java.io.IOException;

public class DataBaseDumpOrBackrout {
    /**
     * @param hostIP ip地址,可以是本机也可以是远程
     * @param userName 数据库的用户名
     * @param password 数据库的密码
     * @param savePath 备份的路径
     * @param fileName 备份的文件名
     * @param databaseName 需要备份的数据库的名称
     * @return
     */
    public static boolean backup(String hostIP, String userName, String password, String savePath, String fileName,
                                 String databaseName) {
        fileName +=".sql";
        File saveFile = new File(savePath);

        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        if (!savePath.endsWith(File.separator)) {
            savePath = savePath + File.separator;
        }

        
        //拼接命令行的命令
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump --opt -h ").append(hostIP);
        stringBuilder.append(" --user=").append(userName).append(" --password=").append(password)
                .append(" --lock-all-tables=true");
        stringBuilder.append(" --result-file=").append(savePath + fileName).append(" --default-character-set=utf8 ")
                .append(databaseName);
        System.out.println(stringBuilder.toString());
        try {
            //调用外部执行exe文件的javaAPI
            Process process = Runtime.getRuntime().exec(stringBuilder.toString());
            
            if (process.waitFor() == 0) {// 0 表示线程正常终止。
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * @param filepath 数据库备份的脚本路径
     * @param ip IP地址
     * @param database 数据库名称
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    public static boolean recover(String filepath,String ip,String database, String userName,String password) {


        String stmt1 = "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqladmin -h "+ip+" -u"+userName+" -p"+password+" create DATABASE if not EXISTS "+database;

        String stmt2 = "mysql -h "+ip+" -u"+userName+" -p"+password+" "+database+" < " + filepath;

        String[] cmd = { "cmd", "/c", stmt2 };

        try {
         System.out.println(stmt1);
            Runtime.getRuntime().exec(stmt1);
            System.out.println(cmd);
            Runtime.getRuntime().exec(cmd);
            System.out.println("数据已从 " + filepath + " 导入到数据库中");
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}

备份的main方法
在这里插入图片描述

package com.company;
/**
 * 
 * @author zndume
 * 数据库备份主方法测试
 *
 */
public class BuckupMain {

    public static void main(String[] args) {
        String hostip = "172.17.7.60";
        String username = "root";
        String password = "zndume";
        String savepath = "D:\\test";
        String filename = "robot-test";
        String databaseName = "robot";
        boolean backup = DataBaseDumpOrBackrout.backup(hostip, username, password, savepath, filename, databaseName);
        System.out.println(backup);
        
    }
}

还原的main方法
在这里插入图片描述


package com.company;

public class RecoverMain {
 
 public static void main(String[] args) {
   String ip = "172.17.7.60";
      String userName = "root";
      String password = "zndume";
      String savepath = "D:\\test\\robot-test.sql";
      String databaseName = "robot-test";
      boolean recover = DataBaseDumpOrBackrout.recover(savepath, ip, databaseName, userName, password);
      System.out.println(recover);
 }
 
 

}

欢迎留言交流,觉得不错就加个关注吧!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小七蒙恩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值