2012-02-01 68 views
1

MySQL数据库的备份,我能够使用mysqldump.exe与下面的Java代码的帮助下创建一个备份我目前的MySQL数据库作为.SQL文件如何恢复使用Java

Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql"); 

现在我想恢复此相同的.SQL备份文件 MySQL数据库使用Java类似于上面的一个按钮点击的事件代码。

感谢很多:)

所以现在我尝试这样做; Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr < C:\\SCM Files\\SQL Backup\\RR.sql"); 仍然没有奏效:/

+0

你是否试过这样的事? – Rocky 2012-02-01 10:09:23

+1

Duplicate:http://stackoverflow.com/questions/4755552/how-to-import-sql-file-to-mysql-dump-using-cammand-line-in-windows(编辑:这不是真的与Java有关,当然可以用这种方式启动任何命令。) – 2012-02-01 10:13:18

回答

2
Runtime.getRuntime().exec("mysql -u username -ppassword database_name FILE.sql") 

本声明将重新生成数据库从文件

+0

更具体地说-e“\。file.sql”或-e“source file.sql”参见[batch-mode](http://dev.mysql.com) /doc/refman/5.5/en/batch-mode.html)但使用字符串数组 – KCD 2012-04-20 04:12:40

0

你应该尝试DbUnit备份和database.Here的恢复是为演示代码:

try { 
     Class.forName(DBDRIVER); 
     Connection jdbcConnection = DriverManager.getConnection(DBURL, DBUSERNAME, DBPASSWORD); 
     IDatabaseConnection connection = new DatabaseConnection(jdbcConnection); 
     connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, 
        new MySqlDataTypeFactory()); 

     //////// Database backup 
     ITableFilter filter = new DatabaseSequenceFilter(connection); 
     IDataSet dataset = new FilteredDataSet(filter, connection.createDataSet()); 

     ExcludeTableFilter excludeFilter = new ExcludeTableFilter(); 
     excludeFilter.excludeTable("DATABASECHANGELOG*"); 
     IDataSet excludedataset = new FilteredDataSet(excludeFilter, dataset); 
     FlatXmlDataSet.write(excludedataset, new FileOutputStream(backupfilename)); 

     System.out.println("\n Complete backup successful."); 
     //////// Database backup 


     //////// Database restore 
     IDataSetProducer producer = new FlatXmlProducer(new InputSource(restoreFileName)); 
     IDataSet dataSet = new StreamingDataSet(producer); 

     TransactionOperation operation = new TransactionOperation(DatabaseOperation.INSERT); 
     operation.execute(connection, dataSet); 
     //////// Database restore 
    } catch (DatabaseUnitException e) { 
     e.printStackTrace(); 
     flag = false; 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 
2

你必须在那里你可以用java波动设计形式。这是一些可以做到的代码。

import javax.swing.JFrame; 

public final class RestoreMySQLDatabase extends JFrame { 
    private static final long serialVersionUID = 1L; 
    public static void main(String[] args) { 
     RestoreMySQLDatabase restoreMySQL = new RestoreMySQLDatabase(); 
     restoreMySQL.setTitle("Restore mysql database"); 
     javax.swing.JButton butRestore = new javax.swing.JButton("Restore"); 
     butRestore.addActionListener(new java.awt.event.ActionListener(){ 
      public void actionPerformed(java.awt.event.ActionEvent event){ 
       try{ 
        Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql"); 
        javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Successfully restored"); 
       }catch(java.lang.Exception e){ 
        javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Not able to restore"); 
       } 
      } 
     }); 
    } 

} 
0

使用相同的转储导入这样。

Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr database_name < "C:\\SCM Files\\SQL Backup\\RR.sql"); 
+0

这不起作用:/ 'Process runProcess = Runtime.getRuntime().exec(“C:\\ SCM Files \ \ SQL备份\\ mysqldump.exe -uroot -p123 rr wishman 2012-02-01 10:48:48

3
public static boolean restoreDB(String dbName, String dbUserName, String dbPassword, String source) { 
String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, dbName,"-e", " source "+source}; 
Process runtimeProcess; 
try { 
runtimeProcess = Runtime.getRuntime().exec(executeCmd); 
int processComplete = runtimeProcess.waitFor(); 
if (processComplete == 0) { 
    System.out.println("Backup restored successfully"); 
    return true; 
} 
} else { 
    System.out.println("Could not restore the backup"); 
     } 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
     return false; 
} 

源例如: “E:\\我的备份\\测试\\ file.sql”

+0

+1 for cmd as a String [] not String – KCD 2012-04-20 04:13:37

0

对于恢复使用在提供的表单m.Torkashvand(字符串数组)的executeCmd。关于如何使用从JSP代码这些命令的工作的例子可以发现here

0
public static void mysqlExport(String host, String port, String user, String password, String dbname, String table, String folder, String query) { 

    System.out.println("------ Exporting "+dbname+"."+table+" at "+folder+"---------------------------"); 
    try { 
     String command = "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " --where=\"" + query + "\" > " + folder + table + ".sql"; 
     System.out.println(command); 
     int returnValue = executeCommand(Arrays.asList("mysqldump", "--host="+host, "--port="+port, "--user="+user, "--password="+password, dbname, table, "--where="+query), folder + table + ".sql"); 
    } catch (Exception e) { 
     System.out.println(e.getMessage()); 
    } 
} 

public static void mysqlImport(String host, String port, String user, String password, String dbname, String table, String folder) { 

    System.out.println("------ Importing "+dbname+"."+table+" at "+folder+"---------------------------"); 
    try { 
     String command = "mysql --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " < " + folder + table + ".sql"; 
     System.out.println(command); 
     int returnValue = executeCommand(new String[]{"mysql", "--host="+host, "--port="+port, "--user=" + user, "--password=" + password, dbname, "-e", "source " + folder + table + ".sql"}); 
    } catch (Exception e) { 
     System.out.println(e.getMessage()); 
    } 
} 

public static int executeCommand(String[] commands) throws IOException 
{ 
    System.out.println(commands.toString()); 
    Process process = Runtime.getRuntime().exec(commands); 
    return dumpProcess(process); 
} 

public static int executeCommand(List<String> commands, String folder) throws IOException 
{ 
    ProcessBuilder builder = new ProcessBuilder(commands); 
    System.out.println(builder.command()); 
    builder.redirectOutput(new File(folder)); 
    Process process = builder.start(); 
    return dumpProcess(process); 
} 

public static int dumpProcess(Process process) throws IOException 
{ 
    int returnValue = -1; 
    try { 
     String s = null; 
     process.waitFor(); 
     returnValue = process.exitValue(); 
     if (returnValue == 0) { 
      System.out.println("Command successful !!"); 
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); 
      System.out.println("Here is the standard output of the command:\n"); 
      while ((s = stdInput.readLine()) != null) { 
       System.out.println(s); 
      } 
     } else { 
      System.out.println("Command failed. Exist Status code = "+returnValue); 
      BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); 
      System.out.println("Here is the standard error of the command (if any):\n"); 
      while ((s = stdError.readLine()) != null) { 
       System.out.println(s); 
      } 
     } 

    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 

    return returnValue; 
} 
0

我尝试此代码,可以作为完美!

String[] restoreCmd = new String[]{"mysql ", "--user=" + DB.DB_USERNAME, "--password=" + DB.DB_PASSWORD, "-e", "source " + pathToFile}; 
    try { 
     Process runtimeProcess = Runtime.getRuntime().exec(restoreCmd); 
     int processComplete = runtimeProcess.waitFor(); 
     if (processComplete == 0) { 
      System.out.println("Done"); 
     } else { 
      System.out.println("Failed"); 
     } 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    }