小编典典

备份mysql数据库的java代码

mysql

我尝试运行以下代码来创建 数据库备份, 但它显示了一些运行时错误。

但是,我尝试 在mysql shell中 运行 System.out.println()输出 部分(在给定的代码中已对此进行了注释)
,并且它可以正常工作

它显示io文件问题。请有人帮助我。

package files;

 public class tableBackup_1 {

public boolean tbBackup(String dbName,String dbUserName, String dbPassword, String path) {

    String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " --add-drop-database -B " + dbName + " -r " + path;
    Process runtimeProcess;
        try
        {
            System.out.println(executeCmd);//this out put works in mysql shell
            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

                if (processComplete == 0)
                {
                    System.out.println("Backup created successfully");
                    return true;
                }
                else
                {
                    System.out.println("Could not create the backup");
                }
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
return false;
}

public static void main(String[] args){

        tableBackup_1 bb = new tableBackup_1();
        bb.tbBackup("test","harin","1234","C:/Users/Master/Downloads/123.sql");

}
}



    mysqldump -u harin -p1234 --add-drop-database -B test -r C:/Users/Master/Downloads/123.sql
java.io.IOException: Cannot run program "mysqldump": CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
        at java.lang.Runtime.exec(Runtime.java:593)
        at java.lang.Runtime.exec(Runtime.java:431)
        at java.lang.Runtime.exec(Runtime.java:328)
        at files.tableBackup_1.tbBackup(tableBackup_1.java:12)
        at files.tableBackup_1.main(tableBackup_1.java:34)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
        at java.lang.ProcessImpl.start(ProcessImpl.java:30)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)
        ... 5 more

阅读 673

收藏
2020-05-17

共1个答案

小编典典

请检查您的Global PATH环境变量是否在其中包含 \ bin(执行echo %PATH%并查看)。有效地,您应该能够在Plain DOS提示符下键入System.out.println()内容,并且应该能够运行它。

即使无法解决问题,也请尝试将代码更改为如下所示执行

runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });

理想情况下,这应该可以解决该问题。

更新:

如果您不在PATH环境变量中,请将代码更改为以下内容

String executeCmd = "<Path to MySQL>/bin/mysqldump -u " + dbUserName + " -p" + dbPassword + " --add-drop-database -B " + dbName + " -r " + path;
2020-05-17