May be turned out to be a silly problem. Here is the code:
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();
}
}
When I run this program to execute the sql script on MySQL, I just only got the output showing the usage information about mysql command, as following: mysql Ver 14.14 Distrib 5.5.44, for debian-linux-gnu (x86_64) using readline 6.3 Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
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.)
The command mysql -h localhost -u root -p admin < ./scripts/atestscript.sql runs perfectly when execute directly through the command line. What is wrong with the program when executing the command by folking a shell process?
I then tried the command mysql -h localhost -u root -p admin -e "source ./scripts/atestscript.sql" in the program, it doesn't work neither.
I also tried using ProcessBuilder by replacing Runtime.getRuntime.exec(command) by the following code:
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();
doesn't work too.
Maybe I just made some tiny mistakes in the program, but I was really stucked on it. Anyone has an idea on the problem?
-hlocalhost,"-u" + username,"-p" + passwordcould be the issue. Do a display ofparamsbefore you are calling ProcessBuilder.. Also, hope you know complexity of what you trying to do..