我尝试使用 Python 和 PymySQL 将两个用户输入值的组合传递到 WHERE
子句中。
我现在的代码是:
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
函数的任何建议吗?
最佳答案
如果允许这样做,可能会存在安全风险。首先,确定,在服务器上,如果这是针对 Web 服务器的,则 sign_input
是 <
之一, =
,和>
。 然后,您可以使用字符串连接( 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
链。
关于python - 将用户值传递给 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56101010/