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

java定时备份数据之二_MySQL

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

以mysql为例:

BackupDb.java数据库备份类:

public class BackupDb {
public static boolean sqlDump(String cmd,String filePath){
boolean falg = false;
try {
Runtime run = Runtime.getRuntime();
Process p = run.exec(cmd);
InputStream is = p.getInputStream();// 控制台的输出信息作为输入流
InputStreamReader isr = new InputStreamReader(is,"UTF-8");//设置输入流编码格式
BufferedReader br = new BufferedReader(isr);
//将控制台输入信息写入到文件输出流中
FileOutputStream fos = new FileOutputStream(filePath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
String temp = null;
while( (temp = br.readLine()) !=null){
bw.write(temp);
bw.newLine();
}
bw.flush();
bw.close();
br.close();
falg = true;
System.out.println("/* Dump SQL File "+filePath+" OK! */");
} catch (IOException e) {
throw new RuntimeException("请将mysql命令添加到path中!",e);
}
return falg;
}
}

pickTask.java类 定时任务类

public class PickTask {
private Timer timer;
public PickTask() {
timer = new Timer();
}
public 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);

BackupDb bdb = new BackupDb();
// 设定备份时间
if (beginTime.equals("17:51")) {
try {
Date date2 = new Date();
SimpleDateFormat sdff = new SimpleDateFormat("yyyyMMddHHmmss");
File file = new File("d://", sdff.format(date2)+".sql");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

//备份 C:/Program Files (x86)/MySQL/MySQL Server 5.5/bin 指mysql安装路径下面的bin文件夹
bdb.sqlDump("C:/Program Files (x86)/MySQL/MySQL Server 5.5/bin/mysqldump -uroot -p123 databasename",file.toString());
System.out.println("备份成功");




String dbName = file.toString(); // 取出备份的文件名字
if (file.exists()){
System.out.println("备份成功");

}else{

System.out.println("备份未成功");
//在备份未成功的情况下重新备份
new PickTask().start(1, 60); //隔60秒执行一次
}
} catch (FileNotFoundException e) {
System.out.println("can not find the file");
} catch (IOException e) {
e.printStackTrace();
}
}else{
//System.out.println("时间还不到呢,不要着急哦!");
}
}
};
public void start(int delay, int internal) {
timer.schedule(task, delay * 1000, internal * 1000);
}
}

人气教程排行