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("== 备份失败!=="); } } }