使用Python3和
cursor.execute(sql, {key1: val1, key2: val2})
语法,我想执行安全(SQL 注入(inject)证明)查询,例如:
SELECT * FROM `table`
WHERE
a = %(fieldA)s AND b IN (%(fieldB)s)
基本上,我正在寻找this question的答案但使用 Python3 语法并使用多个字段。
如果我使用@nosklo的回答:
format_strings = ','.join(['%s'] * len(list_of_ids))
cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings,
tuple(list_of_ids))
1) 如何使用字典语法实现此双重格式化语法 (format_strings, tuple(list_of_ids))
:
cursor.execute(sql, {'field': 'val'})
2)以及当我有多个字段时如何在我的情况下实现它:
cursor.execute(sql, {'x': 'myList', 'y':myOtherVar'})
?
最佳答案
好吧,我想我刚刚发现了:
myList = ["a", "b", "c"]
myStr = "d"
sql = """SELECT * FROM `table`
WHERE
a = %(myStr)s AND b IN %(myList)s"""
cursor.execute(sql, {
myList: myList,
myStr: myStr
})
之前曾尝试过使用 IN (%(myStr)s)
而不是 IN %(myStr)s
。
我仍然不明白为什么有些人声称在这种情况下我们必须使用元组,因为列表工作得非常好。
关于Python3 + DB : "Select * from ` table` where `field` IN (. ..) AND `field2` = '...' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54631815/