您好,欢迎访问一九零五行业门户网

java定时备份数据之二_MySQL

以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);
 }
}
其它类似信息

推荐信息