如何将 mysql 命令传递给 ProcessBuilder

How to pass mysql commands to ProcessBuilder

这是我的:

List<String> restoreCmds = new ArrayList<>();
restoreCmds.add("mysql");
restoreCmds.add("-h" + host);
restoreCmds.add("-u" + login);
restoreCmds.add("-p" + pass);
restoreCmds.add("-e 'source dump.sql'");
restoreCmds.add(targetDB);

ProcessBuilder pb = new ProcessBuilder(restoreCmds);
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
Process pr = pb.start();

int exitVal = pr.waitFor()

我收到以下错误:

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''source dump.sql'' at line 1

您不需要为来源添加引述。

我将线路更改为以下并且它对我有用。

restoreCmds.add("-e source dump.sql");

-e选项用于直接执行指定的命令,如手册中所见:

--execute=statement, -e statement

Execute the statement and quit. Disables --force and history file. The default output format is like that produced with --batch.

您应该使用输入重定向来使用带有 sql 的源文件来执行。

警告:此外,您应该指定要操作的数据库的名称。