2013-02-17 26 views
11

Làm thế nào để sao lưu cơ sở dữ liệu mysql từ một mã java như vậy:Simple Backup và Restore cho cơ sở dữ liệu mysql từ Java

  1. Nó tiết kiệm con đường được cấp phát động.
  2. Dấu cách trong đường dẫn không gây ra sự cố.
  3. Đường dẫn được tạo bằng tệp jar thực thi.
  4. Tên người dùng, DBusername hoặc DBpass được phân bổ động.
  5. Tạo thư mục chuyên biệt để lưu tệp sao lưu.
+0

Hmm phải gimme ngày codez, vì vậy những gì có bạn đã thử? –

+1

Thực ra tôi đã đăng mã để mọi người có thể truy cập vào nó. Có rất nhiều người đang tìm kiếm cùng một câu hỏi (bao gồm cả tôi, đã cho tôi 2 ngày). Vì vậy, điều này là dành cho tất cả những ai cần giúp đỡ – chettyharish

+0

Đủ công bằng, chúng tôi sẽ xem mọi người có thích không. –

Trả lời

20

Lưu ý: Các mã được cung cấp bên dưới là một cách để giải quyết vấn đề và có thể không phải là phương pháp tốt nhất. Mọi thứ đều có thể thay đổi bên trong mã. Nếu bạn không có mysql trong biến môi trường, hãy thêm đường dẫn trước mysqldump và mysql (ví dụ: Đối với XAMPP, C: \ xampp \ mysql \ bin \ mysqldump)

(Hy vọng, điều này sẽ giải quyết được vấn đề của bạn. ngày để hoàn toàn tìm ra tất cả mọi thứ và thực hiện chúng đúng cách)

Phương pháp sao lưu:

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

Phương pháp Restore:

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

phương thức 'Backupdbtosql' của bạn hiển thị lỗi khi được thực hiện. _Error tại BackuprestoreCannot chạy chương trình "mysqldump"; Lỗi CreateProcess = 2, Hệ thống không thể tìm thấy tệp được chỉ định_ –

+0

Tôi đang sử dụng wampserver –

+1

Lỗi đó xảy ra do bạn không đặt đường dẫn mysqldump.exe, tôi đã gặp lỗi tương tự, nhưng mã hóa hoạt động hoàn hảo. Đối với Windows: 'Chuỗi executeCmd =" ​​C: \\ Tệp chương trình (x86) \\ MySQL \\ MySQL Workbench 6.1 CE \\ mysqldump -u "+ dbUser +" -p "+ dbPass +" --database "+ dbName + "-r" + savePath; ' Đây không phải là giải pháp tối ưu, do có vấn đề về prtable! Xin lỗi về tiếng Anh của tôi – vLopez

3

Nếu Hibernate được cấu hình đúng, đây là bánh:

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

Điều này chỉ để đạt được sao lưu, và nó cần thiết lập Hibernate + bạn cần đậu thực hiện tất cả các bảng (có thể là 100) mã khác đơn giản và dễ thực hiện cho người mới (mặc dù không an toàn và không hiệu quả) – chettyharish

+1

Câu hỏi bắt đầu bằng "Cách sao lưu cơ sở dữ liệu mysql từ mã java".Câu trả lời của tôi làm điều đó một cách an toàn và hiệu quả, mà mã khác không, như bạn đã lưu ý. – hd1

+0

+1 không biết điều này là có thể cho đến khi tôi thấy câu trả lời của bạn. – Mukus

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(); 
} 
Các vấn đề liên quan