将用户值传递给 WHERE 子句
Passing user values to WHERE clause
我正在尝试将两个用户输入值的组合传递到 WHERE
子句中,使用 Python 和 PymySQL。
我现在的密码是:
sign_input = input("Please enter <, =, > for population check ")
Pop_Lim = input("Please input a number for population parameter ")
Where_Limit = sign_input +" "+ Pop_Lim
conn = psq.connect("localhost","root","root","City",cursorclass=psq.cursors.DictCursor)
query = "SELECT * FROM city Where Population %s"
with conn:
cursor = conn.cursor()
cursor.execute(query, Where_Limit)
city = cursor.fetchall()
for row in city:
print(row["ID"], row["Name"]," : ",row["CountryCode"]," : ",row["District"]," : ",row["Population"]) # insert spacers for legibility purposes
错误说我提示 Where_Limit 变量有问题。
关于如何解决这个问题,或者将符号和人口变量传递给 SQL 命令中的 Where
函数有什么建议吗?
如果允许,则可能存在安全风险。首先,在服务器上确定,,如果这是一个网络服务器,那么sign_input
是[=12=之一]、=
和 >
。 然后,您可以使用字符串连接 (query = "SELECT * FROM city Where Population " + sign_input + " %s"
) 或一组 if
/elif
语句:
if sign_input == '<':
query = "SELECT * FROM city Where Population < %s"
elif sign_input == '=':
query = "SELECT * FROM city Where Population = %s"
elif sign_input == '>':
query = "SELECT * FROM city Where Population > %s"
连接更短且重复更少,但更容易确保具有常量字符串的 if
/elif
链是安全的。对于 sign_input
和 if
/elif
链使用一组不同的合法值也更容易。
我正在尝试将两个用户输入值的组合传递到 WHERE
子句中,使用 Python 和 PymySQL。
我现在的密码是:
sign_input = input("Please enter <, =, > for population check ")
Pop_Lim = input("Please input a number for population parameter ")
Where_Limit = sign_input +" "+ Pop_Lim
conn = psq.connect("localhost","root","root","City",cursorclass=psq.cursors.DictCursor)
query = "SELECT * FROM city Where Population %s"
with conn:
cursor = conn.cursor()
cursor.execute(query, Where_Limit)
city = cursor.fetchall()
for row in city:
print(row["ID"], row["Name"]," : ",row["CountryCode"]," : ",row["District"]," : ",row["Population"]) # insert spacers for legibility purposes
错误说我提示 Where_Limit 变量有问题。
关于如何解决这个问题,或者将符号和人口变量传递给 SQL 命令中的 Where
函数有什么建议吗?
如果允许,则可能存在安全风险。首先,在服务器上确定,,如果这是一个网络服务器,那么sign_input
是[=12=之一]、=
和 >
。 然后,您可以使用字符串连接 (query = "SELECT * FROM city Where Population " + sign_input + " %s"
) 或一组 if
/elif
语句:
if sign_input == '<':
query = "SELECT * FROM city Where Population < %s"
elif sign_input == '=':
query = "SELECT * FROM city Where Population = %s"
elif sign_input == '>':
query = "SELECT * FROM city Where Population > %s"
连接更短且重复更少,但更容易确保具有常量字符串的 if
/elif
链是安全的。对于 sign_input
和 if
/elif
链使用一组不同的合法值也更容易。