如何使用 channel.connect(); 对远程数据库执行“插入”查询;

How to execute an “insert into” query to a remote database with channel.connect();

这是我试图插入远程数据库 table 的 java 代码。

session.connect();
Channel channel = session.openChannel("exec");

String query = "INSERT INTO table_name
(id,serialno,userid,checktime,checktype,eventType) 
VALUES(502,1011,0078,'2017-04-17 17:27:51',6,23)";

((ChannelExec) channel).setCommand("mysql -uuser -ppwd -h localhost -e'" + 
query + "' database_name");
    InputStream in = channel.getInputStream();
    channel.connect();

我使用相同的代码来执行 "select *" 查询,而不是 "Insert query" 它执行得很好,我得到了输出。但在这种情况下它没有。请帮我找到解决办法。

您是否在命令行中尝试过相同的命令?

mysql -uuser -ppwd -h localhost -e'INSERT INTO table_name (id,serialno,userid,checktime,checktype,eventType) VALUES(502,1011,0078,'2017-04-17 17:27:51',6,23)' database_name

也不行。 INSERT 命令中的引号与包裹 SQL 命令的命令行中的引号冲突。

一种方法是在命令行中使用双引号:

mysql -uuser -ppwd -h localhost -e"INSERT INTO table_name (id,serialno,userid,checktime,checktype,eventType) VALUES(502,1011,0078,'2017-04-17 17:27:51',6,23)" database_name

然后在 Java 中,您必须将这些双引号转义为 \",因为 Java 使用双引号来分隔字符串。

您需要使用 \" 转义双引号,因为双引号在 Java.

中用作分隔符
String query = "INSERT INTO table_name
(id,serialno,userid,checktime,checktype,eventType) 
VALUES(502,1011,0078,'2017-04-17 17:27:51',6,23)"                

((ChannelExec) channel).setCommand("mysql -uroot -proot -h localhost -e\"" + query + "\" yourdbname");