利用dos 命令执行 sql
// 数据库导出
String user = "root"; // 数据库帐号
String password = "xxx"; // 登陆密码
String database = "xxx"; // 需要备份的数据库名
String times= DateUtils.getSpecifyDate(new Date(),"yyyy-MM-dd_HHmmss");
String oldtimes = DateUtils.getSpecifyDate(DateUtils.getPreviousOrNextDaysOfDate(new Date(), -3),"yyyy-MM-dd");
String filepath = "e:\\xxx\\"+times+".sql"; // 备份的路径地址
String stmt1 = "E:\\Program Files\\MariaDB 10.1\\bin\\mysqldump " + database +" -h 192.168.3.120 -u " + user + " -p" + password + " --result-file=" + filepath;
ArrayList<String> imgsrc=new ArrayList<String>();
getAllFileName("e:\\xxx",imgsrc);
imgsrc.parallelStream().forEach(name ->{
if(name.split("_")[0].equals(oldtimes)){
DeleteFileUtil.delete("e:\\xxx\\"+name); // 删除文件 备份文件保留三天
}
});
try {
Runtime.getRuntime().exec(stmt1);
System.out.println("数据已导出到文件" + filepath + "中");
}
catch (IOException e) {
e.printStackTrace();
}
// 获取所有文件名
public static void getAllFileName(String path, ArrayList<String> fileName) {
File file = new File(path);
String[] names = file.list();
if (names != null)
fileName.addAll(Arrays.asList(names));
}
利用jdk 自带timer 实现定时任务
Timer timer = new Timer();
TimerTask t1 = sqlbackup();
timer.schedule(t1, 0, 3600000);