透過 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

相關內容