用java来转储mysql数据库

时间:2015-06-03 14:48:50

标签: java mysqldump

我正在使用Ubuntu。我想用java应用程序来转储MySQL数据库。

以下是我的代码:

String userName = "root";
String userPassword = "root";
String oldDatabaseName = "testing";

String executeCommand = "";
executeCommand = "mysqldump -u "+userName+" -p"+userPassword+" --no-data "       
+OldDatabaseName+" > testingbackup.sql"; 

Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();

if(processComplete == 0){
    System.out.println("Backup successful.");
}else{
    System.out.println("Backup failed.");
}

但是,当我运行上述程序时,我总是收到“备份失败”消息 我写错了代码吗?我需要在我的java应用程序中包含哪些库/文件?
请任何帮助。

2 个答案:

答案 0 :(得分:0)

这在我的Windows机器上工作正常。

   package org.some.test;

   import java.io.File;

   public class dateformat {

    private static final String dbUserName = "root";
    private static final String dbPassword = "manager";
    private static final String dbName = "opencms";

    public static void main(String[] args){

          try {
              File path =new File("D:\\dump1.sql");
                String[] executeCmd = new String[]{"C:/Program Files/MySQL/MySQL Server 5.6/bin/mysql", "--user=" + dbUserName, "--password=" + dbPassword,""+ dbName,"-e", "source "+path};
            Process p = Runtime.getRuntime().exec(executeCmd);
            int processComplete = p.waitFor();
            if (processComplete == 0)
            {
                System.out.println("Restore created successfully");
                //return true;
            }
            else
            {
                System.out.println("Could not restore");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
  }

}

答案 1 :(得分:0)

在我看来,你在-p和quote之间省略了一个空格:

-p "+userPassword+
  ^-- insert space here