从Java代码导入mysql数据库

问题描述:

此代码确实还原了mysql表,但应用程序几乎进入睡眠状态(超过20分钟).并且我的数据库例程不在mysql工作台中,有人可以告诉我实际的解决方案是什么?

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

    String[] executeCmd = new String[]{"C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysql", "--user=" + dbUserName, "--password=" + dbPassword, "-e", "source \"D:/khokher/mydb.sql\""};

    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;
}

使用Runtime.exec方法时,必须从其创建的过程中读取输出.否则,该进程将填充其输出缓冲区,并停止等待,直到通过读取输出清空缓冲区为止.

When using the Runtime.exec method, you have to read the output from the process it creates. Otherwise the process fills its output buffer and stops to wait until you empty the buffer by reading the output.

要读取进程的输出,您可以从exec返回的Process对象获取输入流.您可以从getInputStream返回的流中读取标准输出,并从getErrorStream返回的流中读取标准错误.

To read the output from a process you get the input streams from the Process object that exec returned. You can read the standard output from the stream returned by getInputStream and the standard error from the stream returned by getErrorStream.

如果可以,请使用 Apache Commons Exec 库.它使启动外部流程以及处理其输入和输出变得更加容易.

If you can, use the Apache Commons Exec library. It makes launching an external processes and handling its input and output easier.