Windows下固定周期自动备份mysql数据库

Windows下固定周期自动备份mysql数据库

1.在Java项目中resources目录下创建config.properties用来配置备份数据库相关信息

#备份周期 多长时间备份一次(小时)
frequency=24
#mysqldump 环境位置 指向MYSQL的bin目录下
path=C://Program Files//MySQL//MySQL Server 5.5//bin//
#导出主程序文件名 bin目录下导出程序
exeFile=mysqldump.exe
#导出路径
exportPath=C://JAVA//DBbackup
#导出的数据库 多个用','分割
database=bc,sm,abm
#导出的数据库主机
host=127.0.0.1
#数据库用户名
user=root
#数据库密码
password=12345a

2.将下方代码拷贝到编辑器,打包成可运行jar,使用DOS窗口JAVA - JAR autoBackDB.jar 来运行jar包

public class autobackDB {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("HH_mm_ss");

    String[] exeportDB = null;
    String exportPath = "";
    ReadConfig readConfig = new ReadConfig();
    
    public static void main(String[] args) {
        new autobackDB().execute();
    }

    public void execute(){
        Timer timer1 = new Timer();
        int cycle = Integer.parseInt(readConfig.getPropertiesValue("frequency"));
        timer1.schedule(new TimerTask() {
            public void run() {
                exeportDB = readConfig.getPropertiesValue("database").split(",");
                exportPath = readConfig.getPropertiesValue("exportPath") + simpleDateFormat.format(new Date());
                if(!new File(exportPath).exists()){
                    new File(exportPath).mkdirs();
                }
                String fileTimeSteamp = dateFormat.format(new Date());
                for(String database : exeportDB){
                    String command = "cmd /c cd "+ readConfig.getPropertiesValue("path")+
                            " & "+ readConfig.getPropertiesValue("exeFile")+
                            " -h "+ readConfig.getPropertiesValue("host") +
                            " -u"+ readConfig.getPropertiesValue("user") +
                            " -p"+ readConfig.getPropertiesValue("password") +
                            " " + database + " > " + exportPath + "//" + database + "_" + fileTimeSteamp + ".sql";
                    System.out.println(command);
                    execCMD(command);
                }
            }
        }, 0 , 1000 * 60 * 60 * cycle);
    }

    public void execCMD(String command) {
        try {
            Runtime.getRuntime().exec(command);
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

如果好用,请点个赞呗!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值