当前位置:Gxlcms > mysql > java定时备份数据库_MySQL

java定时备份数据库_MySQL

时间:2021-07-01 10:21:17 帮助过:41人阅读

java数据库定时备份,这里是以mysql为例:

BackupDb.java(数据库备份类)

public class BackupDb {
public String backup() throws IOException{
String user = "root"; //数据库的用户名
String password = "root";//数据库的密码
String database = "database";//要备份的数据库名
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String filepath = "d://jinsus"+sdf.format(date)+".sql";
File file = new File("d://","jinsus"+sdf.format(date)+".sql");
if(!file.exists()){
file.createNewFile();
}
String stmt1 = "mysqldump " + database +" -h 127.0.0.1 "+ " -u " + user + " -p" +
password + " --default-character-set=gbk --result-file=" + filepath;
try {
Runtime.getRuntime().exec(stmt1);
System.out.println("已经保存到 " + filepath + " 中");
} catch (IOException e) {
e.printStackTrace();
}
return filepath;
}
}

TimerUse.java(定时及测试类)

public class TimerUse {
public static void main(String[] args) {
PickTask picktask = new PickTask();
picktask.start(1, 60); // 每60秒执行一次
}
}

class PickTask {
private Timer timer;
private TimerTask task = new TimerTask() {
public void run() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String beginDate = sdf.format(date);
String beginTime = beginDate.substring(11, 16);
System.out.println("开始时间:"+beginDate);

BackupDb bdb = new BackupDb();
// 设定备份时间
if (beginTime.equals("16:39")) {
try {
bdb.backup(); // 执行文件备份
String dbName = bdb.backup().toString(); // 取出备份的文件名字
String path = "d://";
int nameNo = dbName.lastIndexOf("//");
//判断文件是否存在,如果存在,则备份成功,如果不存在则备份不成功需要重新备份
File file = new File(path, dbName.substring(nameNo + 1,
dbName.length()));
if (file.exists()){
system.out.println("备份成功");

}else{

system.out.println("备份失败,重新备份");
//在备份未成功的情况下重新备份
new PickTask().start(1, 1);
}

} catch (FileNotFoundException e) {
System.out.println("can not find the file");
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("时间还不到呢,不要着急哦!");
}
}
};

//start 方法不能少,主要是schedule方法
public void start(int delay, int internal) {
timer.schedule(task, delay * 1000, internal * 1000);
}
}

人气教程排行