来自java应用程序的mysqldump

blu*_*ony 3 java mysqldump

尝试使用以下命令从Java应用程序(IDE Netbeans)备份mysql数据库,但即使我指定了路径,也似乎无法找到该文件:

Runtime.getRuntime().exec("C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump "+fisier.getName()+" > C:\\"+fisier.getName()+".sql;");
Run Code Online (Sandbox Code Playgroud)

此外,我没有收到任何错误,所以我认为备份已经完成.我怎样才能找到该文件?关于fisier.getName():File fisier = jFileChooserSave.getSelectedFile();

Sta*_*ler 7

对于非Windows用户:

String dump = "mysqldump -usome_user -psome_pass database_name   > path/to/file.sql";
String[] cmdarray = {"/bin/sh","-c", dump};
Process p = Runtime.getRuntime().exec(cmdarray);
if (p.waitFor() == 0) {
    // Everything went fine
} else {
   // Something went wrong
}
Run Code Online (Sandbox Code Playgroud)

使用cmd数组非常重要.否则exec无法解析'>'和文件名,您将收到错误.


San*_*ikh 6

您可以测试下面提到的代码来测试mysqldump命令输出.根据我的假设,文件没有创建的原因有两个主要原因: -

  1. 如果使用Windows,那么目标位置的UAC权限可能是问题.
  2. 您可能在生成的最终mysqldump命令中面临语法问题,该命令由Java运行时执行.

     //Process exec = Runtime.getRuntime().exec("C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump "+fisier.getName()+" > C:\\"+fisier.getName()+".sql;");
    
    Process exec = Runtime.getRuntime().exec(new String[]{"cmd.exe","/c","C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump "+fisier.getName()+" > C:\\"+fisier.getName()+".sql;"});
    
    //Wait for the command to complete, and check if the exit value was 0 (success)
    if(exec.waitFor()==0)
    {
        //normally terminated, a way to read the output
        InputStream inputStream = exec.getInputStream();
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
    
        String str = new String(buffer);
        System.out.println(str);
    }
    else
    {
        // abnormally terminated, there was some problem
                    //a way to read the error during the execution of the command
        InputStream errorStream = exec.getErrorStream();
        byte[] buffer = new byte[errorStream.available()];
        errorStream.read(buffer);
    
        String str = new String(buffer);
        System.out.println(str);
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

使用时,重定向运算符不起作用 Process exec = Runtime.getRuntime().exec("C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump "+fisier.getName()+" > C:\\"+fisier.getName()+".sql;");

因为它不会调用命令shell,所以我们无法获得重定向运算符的功能,为了解决这个问题,我们可以执行命令提示符(cmd),然后执行mysqldump命令,它就可以了.

Process exec = Runtime.getRuntime().exec(new String[]{"cmd.exe","/c","C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump "+fisier.getName()+" > C:\\"+fisier.getName()+".sql;"});

cmd.exe中的/ c指定执行传递的命令并终止进程.java运行时执行的实际命令将成为

cmd.exe/c yourmysqldumpCommand