通过SSH执行远程MySQL查询

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

 ssh -p 2020 mysql@mysql1.local.mydomain.com "mysql --verbose --compress --secure-auth --database ops --execute \ 'INSERT INTO \`ops\`.\`accounts\` (\`alias\`, \`id\`, \`web_server\`, \`mysql_server\`) VALUES ('foobar', 'foobar', 'web2', 'mysql1')'" 

问题是,当这个被执行时, foobarfoobarweb2mysql1的单引号被删除。 这里是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) -------------- 

我怎样才能解决这个问题? 谢谢。

解决方法是在值的附近添加另一层转义的单引号。

 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\'')'" 

以下应该工作:

 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] 

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

 $ mysql --host localhost --port 2206