1

当我使用值作为变量从 shell 脚本执行 MySQL 查询时,它显示

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 '@gmail.com' at line 1

我的代码

#!/bin/bash

email='new_user@gmail.com'

# Checking - is the email already exists,
email_exists=$(mysql -u username -ppassword -e "SELECT id FROM db.user where email=$email;")

使用内联(不使用变量)时没问题。

仅供参考:我使用电子邮件作为变量,因为我需要在代码中的某个地方重用。

4

2 回答 2

1

在字符串周围添加单引号(在现有的双引号内)以使其有效 SQL:

email_exists=$(mysql -u username -ppassword -e "SELECT id FROM db.user where email='$email';")

也就是说,请注意,只有当您控制字符串并确定其内容中不包含任何文字引号时,这才是安全的。(new_user@gmail.com是安全的,但new_user@gmail.com'; DROP TABLE db; -- '不会)。Bill Kelwin 关于“命令行中的注入证明 SQL 语句”的回答提供了一种避免这种陷阱的方法。

于 2020-07-29T11:48:33.737 回答
1

单引号和双引号在 bash 中用于转义某些字符,它们不用于表示字符串。您的情况下的单引号不会在您的 mysql 语句中使用,因此您会收到语法错误(您的 mysql 语句没有字符串)。

#!/bin/bash

email=new_user@gmail.com

# Checking - is the email already exists,
email_exists=$(mysql -u username -ppassword -e "SELECT id FROM db.user where email='$email';")
于 2020-07-29T11:48:42.720 回答