java 备份数据库

复制代码
package com.common.taskTiming;

import com.common.utils.DateFormatter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

/**
 * @author Mongo
 * @date 2022-4-29-0029 下午 9:27:25
 * @Email mongo_chen@wesurance.io
 * @return
 */
@Slf4j
public class BackupUtil {

    private static final String dbBinPath = "D:\\mysql-5.6.40-winx64\\bin";
    private static final String savePath = "D:\\a_db_backup\\";
    private static final String ipPath = null;
       
    private String user_name;//数据库用户名
    private String user_psw;//数据库密码
    private String db_name;//需要备份的数据库名
    private String host_ip;//主机IP
    private String user_charset;//字符集
    private String backup_path;//存放备份文件的路径
    private String stmt;//命令

    public BackupUtil(String dbBinPath,String user_name, String user_psw, String db_name,
                      String host_ip, String user_charset, String backup_path) {
        this.user_name = user_name;
        this.user_psw = user_psw;
        this.db_name = db_name;
        // 主机IP;
        if (StringUtils.isBlank(host_ip)) {
            // 默认为本机
            this.host_ip = "localhost";
        } else {
            this.host_ip = host_ip;
        }
        // 字符集
        if (StringUtils.isBlank(user_charset)) {
            // 默认为安装时设置的字符集
            this.user_charset = " ";
        } else {
            this.user_charset = " --default-character-set=" + user_charset;
        }
        this.backup_path = backup_path;
        this.stmt = dbBinPath + "\\mysqldump "
                + this.db_name 
                + " -h " + this.host_ip 
                + " -u" + this.user_name
                + " -p" + this.user_psw 
                + this.user_charset + " --result-file="
                + this.backup_path;
    }

    public boolean backup_run() {
        boolean run_result = false;
        try {
            Runtime.getRuntime().exec(this.stmt);
            run_result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return run_result;
    }

    public static void main(String[] args) {

        String time = DateFormatter.getStringByDate(new DateFormatter().yyyyMMdd_HHmmss,new Date());
        BackupUtil backup = new BackupUtil("root",//账号 
                                "1234", //密码
                                "store", //库名
                                ipPath , //ip地址(默认本机)
                                "utf8mb4",//字符集
                savePath + "db_store_"+time+".sql");
        boolean result = backup.backup_run();
        if (result) {
            log.info("== 备份成功!==");
        }else{
            log.info("== 备份失败!==");
        }
    }
    
}
复制代码

 

posted @   雪化山河  阅读(602)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 我与微信审核的“相爱相杀”看个人小程序副业
· DeepSeek “源神”启动!「GitHub 热点速览」
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示