>  기사  >  데이터 베이스  >  java定时备份数据之二_MySQL

java定时备份数据之二_MySQL

WBOY
WBOY원래의
2016-06-01 13:07:481068검색

以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);
 }
}

 

 

 

 

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.