将用户值传递到WHERE子句

时间:2019-05-12 16:00:51

标签: python pymysql

我正在尝试使用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函数的任何建议?

1 个答案:

答案 0 :(得分:2)

如果允许这样做,则可能会带来安全风险。首先,确保确定,在服务器上 ,如果这是针对Web服务器的,则sign_input<,{{1}中的一个}和=然后,您可以使用字符串串联(>)或一组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使用一组不同的合法值也更容易。