2013-02-17 72 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(); 
}