// 备份文件存放路径,我这里以当前日期作为文件夹
String root = JRelaxSystemConfigHelper.get("upload.folder.root", JRelaxCoreConfigHelper.getProperty("resource.upload.path"));
String uploadPath = JRelaxIOHelper.getInstance().resolvePath(root) + "mysqlbak/" + DateKit.format(new Date(), "yyyyMMdd");
String dbhost = "127.0.0.1";
String dbname = "dbname";//要备份的数据库名称
String dbusername = "dbusername";//数据库用户名
String dbpassword = "dbpassword";//数据库密码
System.err.println(StringKit.format("-------------获取到备份数据库: {0},{1},{2}", dbname, dbusername, dbpassword));
// 备份文件名称
String backName = dbname + "_" + dbhost + "_" + DateKit.format(new Date(), DateKit.HHMM) + ".sql";
String pathSql = uploadPath + "/" + backName;
try {
File fileSql = new File(pathSql);
// 创建备份sql文件
if (!fileSql.getParentFile().exists()) {
if (!fileSql.getParentFile().mkdirs()) {
throw new IOException("文件夹创建失败");
}
}
StringBuffer sb = new StringBuffer();
sb.append("mysqldump");
if(!"127.0.0.1".equals(dbhost))
sb.append(" -h " + dbhost);
sb.append(" -u" + dbusername);
sb.append(" -p" + dbpassword);
sb.append(" --databases " + dbname);
//如果要过滤掉部分表不备份,可以通过--ignore-table参数
String[] ignoreTables = { "sys_log", "sys_scheduler_log", "sys_file" , "sys_user"};
for (String ignoreTable : ignoreTables) {
sb.append(" --ignore-table=" + dbname + "." + ignoreTable);
}
sb.append(" >");
sb.append(pathSql);
System.err.println("cmd命令为:" + sb.toString());
Runtime runtime = Runtime.getRuntime();
//执行备份命令
runtime.exec("cmd /c" + sb.toString());
//打日志
logService.info("数据库备份", StringKit.format("定时备份数据库成功:{0},{1},{2}", dbname, dbhost, backName), "schedule", new HandlerRequest());
} catch (Exception e) {
e.printStackTrace();
logService.info("数据库备份", StringKit.format("定时备份数据库失败:{0},{1},{2}_{3}", dbname, dbhost, backName,e.getMessage()), "schedule", new HandlerRequest());
}