查看您的示例,您似乎正在尝试在 mysql 上运行 sql 命令。
首先,如果您真的想使用 msqyl 命令行命令执行此操作,您希望将其输入/输出重定向到 java InputStream/OutputStream,然后将您的 SQL 请求发送到 mysql 进程输入。您可能会遵循以下示例:
List<String> command = new ArrayList<>();
command.add("mysql -u root -p ********");
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
PrintStream commandIn = new PrintStream(process.getOutputStream());
commandIn.println("select * from employee;");
在 mysql 实例上运行 SQL 命令的第二个最佳方法是使用 JDBC 而不是 mysql 命令行工具。寻找大量的 JDBC 教程。
这是一个更完整(且有效)的示例。
看看这个“命令行工具”:
public class TestCmd {
public static void main(String[] args) throws IOException
{
System.out.println("Started. args[0]=" + args[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for(;;)
{
String line = in.readLine();
if (line == null) break;
System.out.println("echo:" + line);
}
}
}
然后“驱动程序”程序女巫演示了如何向这个命令行工具发送命令:
public class TestDriver {
final static String JAVA_EXE = "C:\\...\\java.exe";
final static String CLASS_BASEPATH = "C:\\...\\java\\bin";
public static void main(String[] args) throws Exception
{
List<String> command = new ArrayList<>();
command.add(JAVA_EXE.toString());
command.add("-classpath");
command.add(CLASS_BASEPATH);
command.add("TestCmd");
command.add("Parameter");
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectOutput(new File("c:\\temp\\out.txt"));
Process process = pb.start();
PrintStream commandIn = new PrintStream(process.getOutputStream());
commandIn.println("first input line");
commandIn.flush();
commandIn.println("second input line");
commandIn.flush();
// give some time to the sub process to finish writing its output
Thread.sleep(100);
process.destroy();
}
}
在输出“out.txt”中你会得到,正如预期的那样:
Started. args[0]=Parameter
echo:first input line
echo:second input line