使用java命令在mysql中恢复数据库

时间:2014-02-22 06:27:51

标签: java mysql

我的使用java命令恢复mysql数据库的代码。

当我调试代码时,它会在运行时停止运行Process.waitFor();

任何人都可以为这个问题提供解决方案吗?

public static boolean restoreDB(String dbUserName, String dbPassword,String dbName, String path) {

    String command ="mysql -u"+dbUserName+" -p"+dbPassword+" "+dbName+" < \""+path+"\"";

    Process runtimeProcess;
    try {

        runtimeProcess = Runtime.getRuntime().exec(command);
        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;
}

2 个答案:

答案 0 :(得分:0)

该过程可能阻止等待输入,或者它已写入如此多的输出,它已填满进程输出缓冲区并等待您读取输出。无论哪种方式,如果您确保打印出该过程的stdout和stderr,您可以获得更多信息:

private static class StreamReader implements Runnable {

    private InputStream stream;
    private volatile boolean finished = false;

    public StreamReader(InputStream stream) {
        this.stream = stream;
    }

    public void run() {
        Scanner scanner = new Scanner(stream);

        while(!finished) {
            System.out.println(scanner.nextLine());          
        }

    }

}

//...
runtimeProcess = Runtime.getRuntime().exec(command);
StreamReader stdoutReader = new StreamReader(runtimeProcess.getInputStream());
StreamReader stderrReader = new StreamReader(runtimeProcess.getErrorStream());
new Thread(stdoutReader).start();
new Thread(stderrReader).start();
int processComplete = -1;
try {
    processComplete = runtimeProcess.waitFor();
} finally {
    stdoutReader.finished = true;
    stderrReader.finished = true;
}

答案 1 :(得分:0)

最后我找到了答案.. 谢谢你们的支持, 我见过很多人都有同样的问题,所以这是我的解决方案

我们无法使用Runtime.getRuntime()。exec()函数执行mysql restore命令。

所以我创建了一个批处理文件,并在其中添加了这个mysql restore命令并执行它。它的工作正常。 :)

public static void restoreDB(String dbUserName, String dbPassword,String dbName, String path) {
    try{
        //for linux .bat must replaced with .sh
        String destpath = "D:\\backup\\db.bat";

    //creating batch file 
    PrintWriter writer = new PrintWriter(destpath);
    String command = "mysql -u"+dbUserName+" -p"+dbPassword+" "+dbName+" < \""+path+"\"";
    writer.println(command);
    writer.close();

    //executing batch file
    Process run = Runtime.getRuntime().exec(destpath);
    System.out.println("file created");
    int processComplete = run.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();
    }

}