可能被证明是个愚蠢的问题。以下是代码:
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要害5.5.44,使用readline6.3版权(c) 2000、2015、Oracle和/或其附属机构的debian gnu (x86_64)。版权所有。
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();也不管用。
也许我只是在程序中犯了一些小小的错误,但我真的被它塞了进去。有人对这个问题有想法吗?
发布于 2015-09-24 05:36:36
我会将ProcessBuilder与sh、-c和mysql -hlocalhost -uroot -padmin < ./scripts/atestscript.sql并列使用。不要忘记第三段的引号。
https://stackoverflow.com/questions/32745525
复制相似问题