无法通过java Runtime或ProcessBuilder执行mysql命令

时间:2015-09-23 17:10:01

标签: java mysql shell

可能会变成一个愚蠢的问题。 这是代码:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws Exception{
        String command = "mysql -hlocalhost -uroot -padmin < ./scripts/atestscript.sql";
//      command = "cat < ./scripts/atestscript.sql";
        Process p = Runtime.getRuntime().exec(command);


        InputStream inputstream = p.getInputStream();
        InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

        // read the output
        String line;
        while ((line = bufferedreader.readLine()) != null) {
            System.out.println(line);
        }

        p.waitFor();
    }
}

当我运行这个程序来执行MySQL上的sql脚本时,我只得到输出显示 mysql 命令的用法信息,如下所示:     mysql Ver 14.14使用readline 6.3为debian-linux-gnu(x86_64)分发5.5.44     版权所有(c)2000,2015,Oracle和/或其附属公司。保留所有权利。

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Usage: mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
                      (Defaults to on; use --skip-auto-rehash to disable.)

命令mysql -h localhost -u root -p admin < ./scripts/atestscript.sql在通过命令行直接执行时运行完美。通过分析shell进程执行命令时程序有什么问题?

然后我在程序中尝试了mysql -h localhost -u root -p admin -e "source ./scripts/atestscript.sql"命令,它既不起作用。

我还尝试使用ProcessBuilder,将Runtime.getRuntime.exec(command)替换为以下代码:

        List<String> params = new ArrayList<String>();
        params.add("/usr/bin/mysql");
        params.add("-hlocalhost");
        params.add("-u" + username);
        params.add("-p" + password);
//      params.add("-e");
//      params.add("\"SOURCE " + filePath + "\"");
        params.add("<");
        params.add(filePath);

        ProcessBuilder pb = new ProcessBuilder(params);
        Process p = pb.redirectErrorStream(true).start();
        int state = p.waitFor();

也不起作用。

也许我只是在程序中犯了一些小错误,但我真的被它搞砸了。有人对这个问题有所了解吗?

1 个答案:

答案 0 :(得分:2)

我会使用带有参数sh-cmysql -hlocalhost -uroot -padmin < ./scripts/atestscript.sql的ProcessBuilder。不要忘记第3个参数上的引号。