通过 SSH 执行远程 MySQL 查询

通过 SSH 执行远程 MySQL 查询

我正在尝试使用以下命令执行MySQL查询:ssh

ssh -p 2020 [email protected] "mysql --verbose --compress --secure-auth --database ops --execute \
'INSERT INTO \`ops\`.\`accounts\` (\`alias\`, \`id\`, \`web_server\`, \`mysql_server\`) VALUES ('foobar', 'foobar', 'web2', 'mysql1')'"

问题是,执行此操作时, 、 、 和 周围的单引号foobarfoobarweb2删除mysql1。以下是来自 MySQL 的错误响应:

ERROR 1054 (42S22) at line 1: Unknown column 'foobar' in 'field list'
--------------
INSERT INTO `ops`.`accounts` (`alias`, `id`, `web_server`, `mysql_server`) VALUES (foobar, foobar, web2, mysql1)
--------------

我该如何修复这个问题?谢谢。

答案1

解决方案是在值周围添加另一层转义的单引号。

ssh -p 2020 [email protected] "mysql --verbose --compress --secure-auth --database ops --execute \
'INSERT INTO \`ops\`.\`accounts\` (\`alias\`, \`id\`, \`web_server\`, \`mysql_server\`) VALUES ('\'foobar\'', '\'foobar\'', '\'web2\'', '\'mysql1\'')'"

答案2

以下应该有效:

echo "INSERT INTO `ops`.`accounts` (`alias`, `id`, `web_server`, `mysql_server`) VALUES ('foobar', 'foobar', 'web2', 'mysql1')" | ssh [email protected] "mysql --verbose --compress --secure-auth --database ops"

您还可以将本地端口转发到远程服务器:

$ ssh -L2206:localhost:3306 [email protected]

然后,在另一个终端中,您将能够使用以下mysql命令连接远程 MySQL 服务器:

$ mysql --host localhost --port 2206

相关内容