1. 程式人生 > >java操作數據庫定時備份與還原

java操作數據庫定時備份與還原

名稱 數據 rri att trac catch form number ride

mysql每天23:00自動備份

  1. public class DatabaseBackup {
  2. /**
  3. *
  4. * @param dbdir mysql數據庫安裝路徑
  5. * @param dbname 數據庫的名稱
  6. * @param backdir 備份的目錄
  7. */
  8. public static void backup(String dbdir, String dbname, String backdir) {
  9. Calendar calendar = Calendar.getInstance();
  10. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HHmmss");
  11. String currentTime = dateFormat.format(calendar.getTime());
  12. try {
  13. long startTime = System.currentTimeMillis();
  14. Runtime rt = Runtime.getRuntime();
  15. Process child = rt
  16. .exec(dbdir + "/bin/mysqldump --default-character-set=utf8 -uroot -p123456 " + dbname);
  17. InputStream in = child.getInputStream();
  18. InputStreamReader xx = new InputStreamReader(in, "utf8");
  19. FileOutputStream fout = new FileOutputStream(new File(backdir, dbname + "_" + currentTime + ".bak"));
  20. OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
  21. dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  22. writer.write("-- Dump by Microsoul at " + dateFormat.format(calendar.getTime()) + "\r\n");
  23. String inStr;
  24. BufferedReader br = new BufferedReader(xx);
  25. // 這樣實時寫入文件很重要,網上有很多是將讀取的存入字符串中,最後再寫成文件,這樣會導致Java的堆棧內存溢出。
  26. while ((inStr = br.readLine()) != null) {
  27. writer.write(inStr);
  28. writer.write("\r\n");
  29. }
  30. writer.write("\r\n-- Use " + (System.currentTimeMillis() - startTime) + "ms\r\n");
  31. writer.flush();
  32. in.close();
  33. xx.close();
  34. br.close();
  35. writer.close();
  36. fout.close();
  37. } catch (Exception e) {
  38. PrintStream print = null;
  39. try {
  40. print = new PrintStream(new File(backdir, currentTime + "_backup_err.log"));
  41. dateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
  42. currentTime = dateFormat.format(calendar.getTime());
  43. print.println(currentTime + " backup failed.");
  44. e.printStackTrace(print);
  45. print.flush();
  46. } catch (IOException e2) {
  47. } finally {
  48. if (print != null) {
  49. print.close();
  50. }
  51. }
  52. }
  53. }
  54. }

以上是備份的代碼;

Java代碼 技術分享
  1. public class Test {
  2. public static void main(String[] args) {
  3. Calendar twentyOne = Calendar.getInstance();
  4. twentyOne.set(Calendar.HOUR_OF_DAY, 23);
  5. twentyOne.set(Calendar.MINUTE, 0);
  6. twentyOne.set(Calendar.SECOND, 0);
  7. new Timer().schedule(new TimerTask() {
  8. @Override
  9. public void run() {
  10. DatabaseBackup.backup("/usr/local/mysql", "test", "/home/xtiger/db/");
  11. }
  12. }, twentyOne.getTime(), 24 * 3600 * 1000);
  13. }
  14. }

java操作數據庫定時備份與還原