python - 将用户值传递给 WHERE 子句

标签 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 函数的任何建议吗?

最佳答案

如果允许这样做,可能会存在安全风险。首先,确定在服务器上,如果这是针对 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/

相关文章:

创建集合的 Python 性能比较 - set() 与 {} 文字

python - 如何检查数据库是否存在于 PyMySQL 中

python - 如果不满足条件,则返回该用户的数据,否则另一个查询

python - Python 如何如此快速地从列表中删除元素?

python - 导出按钮在 django-import-export 包中不可见

python - 解析 JSON 时出现 TypeError : list indices must be integers or slices, not str

python - 如何使用 PyMySQL 将 Pandas Dataframe 插入 MySql

即使使用 sudo,MySQL 也无法以 root 身份登录本地主机

python - 在 SQL 查询中使用 Python 列表获取列名

python - 当我使用 pygame.transform.rotate() 时,它会移动我的图像,这样,如果连续使用,它将离开屏幕。为什么?