2013-02-17 73 views
11

如何從java代碼備份mysql數據庫,從而爲MySQL數據庫還原:簡單備份,並從Java

  1. 它的保存路徑是動態分配的。
  2. Path中的空格不會產生問題。
  3. 使用正在執行的jar文件生成路徑。
  4. 動態分配DBname,DBusername或DBpass。
  5. 創建一個專門的文件夾來保存備份文件。
+0

嗯必須給我的codez一天,所以你嘗試過什麼? – 2013-02-17 18:59:06

+1

其實我已經發布了代碼,以便任何人都可以訪問它。有很多人在尋找相同的問題(包括我,花了我2​​天)。所以這是所有需要幫助的人 – chettyharish 2013-02-17 19:01:35

+0

夠公平的,我們會看看人們是否喜歡它。 – 2013-02-17 22:37:30

回答

20

注:下面給出的代碼是解決問題的一種方式,可能不是最好的方法。代碼內部的一切都是可變的。如果你在環境變量中沒有mysql,在mysqldump和mysql之前添加路徑(例如,對於XAMPP,C:\ xampp \ mysql \ bin \ mysqldump)

(希望這會解決你的問題。天完全弄清楚一切,並正確地執行它們)進行備份

方法:

public static void Backupdbtosql() { 
    try { 

     /*NOTE: Getting path to the Jar file being executed*/ 
     /*NOTE: YourImplementingClass-> replace with the class executing the code*/ 
     CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource(); 
     File jarFile = new File(codeSource.getLocation().toURI().getPath()); 
     String jarDir = jarFile.getParentFile().getPath(); 


     /*NOTE: Creating Database Constraints*/ 
     String dbName = "YourDBName"; 
     String dbUser = "YourUserName"; 
     String dbPass = "YourUserPassword"; 

     /*NOTE: Creating Path Constraints for folder saving*/ 
     /*NOTE: Here the backup folder is created for saving inside it*/ 
     String folderPath = jarDir + "\\backup"; 

     /*NOTE: Creating Folder if it does not exist*/ 
     File f1 = new File(folderPath); 
     f1.mkdir(); 

     /*NOTE: Creating Path Constraints for backup saving*/ 
     /*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/ 
     String savePath = "\"" + jarDir + "\\backup\\" + "backup.sql\""; 

     /*NOTE: Used to create a cmd command*/ 
     String executeCmd = "mysqldump -u" + dbUser + " -p" + dbPass + " --database " + dbName + " -r " + savePath; 

     /*NOTE: Executing the command here*/ 
     Process runtimeProcess = Runtime.getRuntime().exec(executeCmd); 
     int processComplete = runtimeProcess.waitFor(); 

     /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/ 
     if (processComplete == 0) { 
      System.out.println("Backup Complete"); 
     } else { 
      System.out.println("Backup Failure"); 
     } 

    } catch (URISyntaxException | IOException | InterruptedException ex) { 
     JOptionPane.showMessageDialog(null, "Error at Backuprestore" + ex.getMessage()); 
    } 
} 

方法還原:

public static void Restoredbfromsql(String s) { 
     try { 
      /*NOTE: String s is the mysql file name including the .sql in its name*/ 
      /*NOTE: Getting path to the Jar file being executed*/ 
      /*NOTE: YourImplementingClass-> replace with the class executing the code*/ 
      CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource(); 
      File jarFile = new File(codeSource.getLocation().toURI().getPath()); 
      String jarDir = jarFile.getParentFile().getPath(); 

      /*NOTE: Creating Database Constraints*/ 
      String dbName = "YourDBName"; 
      String dbUser = "YourUserName"; 
      String dbPass = "YourUserPassword"; 

      /*NOTE: Creating Path Constraints for restoring*/ 
      String restorePath = jarDir + "\\backup" + "\\" + s; 

      /*NOTE: Used to create a cmd command*/ 
      /*NOTE: Do not create a single large string, this will cause buffer locking, use string array*/ 
      String[] executeCmd = new String[]{"mysql", dbName, "-u" + dbUser, "-p" + dbPass, "-e", " source " + restorePath}; 

      /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/ 
      Process runtimeProcess = Runtime.getRuntime().exec(executeCmd); 
      int processComplete = runtimeProcess.waitFor(); 

      /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/ 
      if (processComplete == 0) { 
       JOptionPane.showMessageDialog(null, "Successfully restored from SQL : " + s); 
      } else { 
       JOptionPane.showMessageDialog(null, "Error at restoring"); 
      } 


     } catch (URISyntaxException | IOException | InterruptedException | HeadlessException ex) { 
      JOptionPane.showMessageDialog(null, "Error at Restoredbfromsql" + ex.getMessage()); 
     } 

    } 
+0

你的方法'Backupdbtosql'在執行時顯示錯誤。 Backuprestore上的錯誤無法運行程序「mysqldump」; CreateProcess error = 2,系統無法找到指定的文件_ – 2016-02-18 20:21:37

+0

我正在使用wampserver – 2016-02-18 20:23:14

+1

由於您沒有放置mysqldump.exe的路徑,所以出現此錯誤,我遇到了同樣的錯誤,但對它進行了編碼,效果很好。對於Windows: 'String executeCmd =「C:\\ Program Files(x86)\\ MySQL \\ MySQL Workbench 6.1 CE \\ mysqldump -u」+ dbUser +「-p」+ dbPass +「--database」+ dbName +「-r」+ savePath;' 這不是一個最佳的解決方案,由於可解決的問題! 對不起,我的英語 – vLopez 2016-07-04 13:33:56

3

如果Hibernate配置正確,這是蛋糕:

Session session = HibernateUtil.getSessionFactory().openSession(); 
// for every table, have the bean implement Serializable and use the next 4 lines 
List <TblBean> tblCollection = session.createCriteria(TblBean.class).list(); 
FileOutputStream backup = new FileOutputStream("backupOf"+TblBean.getClass().getName()+".dat"); 
ObjectOutputStream backupWriter = new ObjectOutputStream(backup); 
backupWriter.write(tblCollection); 
+1

這只是爲了實現備份,它需要設置Hibernate +,你需要bean實現所有的表(可能有100個),其他代碼很簡單,易於實現新手(儘管不安全和低效) – chettyharish 2013-02-17 19:18:24

+1

問題從「如何從java代碼備份mysql數據庫」開始。我的回答是以安全和有效的方式進行的,其他代碼沒有這樣做,正如您所指出的那樣。 – hd1 2013-02-17 19:21:16

+0

+1不知道這是可能的,直到我看到你的答案。 – Mukus 2014-04-06 23:37:32

0
public static String getData(String host, String port, String user, String password, String db,String table) throws Exception { 

    //an "C:/xampp/mysql/bin/mysqldump" ---- location ito han mysqldump 

    Process run = Runtime.getRuntime().exec(
      "C:/xampp/mysql/bin/mysqldump --host=" + host + " --port=" + port + 
      " --user=" + user + " --password=" + password + 
      " --compact --databases --add-drop-table --complete-insert --extended-insert " + 
      "--skip-comments --skip-triggers "+ db+" --tables "+table); 

    InputStream in = run.getInputStream(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
    StringBuffer temp = new StringBuffer(); 
    int count; 
    char[] cbuf = new char[BUFFER]; 

    while ((count = br.read(cbuf, 0, BUFFER)) != -1) 
     temp.append(cbuf, 0, count); 

    br.close(); 
    in.close(); 

    return temp.toString(); 
}