我知道如何将列表Map到字符串:
foostring = ",".join( map(str, list_of_ids) )
我知道我可以使用以下代码将该字符串放入IN子句:
cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring))
我需要的是使用MySQL数据库安全地完成同样的事情(避免SQL注入)。在上面的例子中,因为foostring没有作为参数传递给执行,所以它很容易受到攻击。我还必须引用并退出MySQL库。
(有一个related SO question,但那里列出的答案要么不适用于MySQL数据库,要么容易受到SQL注入的攻击。
9条答案
按热度按时间np8igboo1#
直接使用
list_of_ids
:这样你就不必引用自己的话,也避免了各种各样的sql注入。
注意,数据(
list_of_ids
)作为参数(不在查询文本中)直接进入mysql的驱动程序,因此没有注入。你可以在字符串中保留任何你想要的字符,不需要删除或引用字符。e0uiprwp2#
虽然这个问题是相当老,认为这将是更好地留下回应的情况下,其他人正在寻找我想要的
当我们有很多参数或者我们想使用命名参数时,接受的答案会变得混乱
经过一些试验
使用
python2.7
、pymysql==0.7.11
进行测试vhipe2zx3#
这似乎仍然是Python3在2021年的问题,正如Rubms在评论markk的答案时指出的那样。
在mysql连接器包中的“www.example.com”中的方法“_process_params_dict”添加了大约9行代码cursor.py来处理元组,为我解决了这个问题:
sigwle7e4#
也许这个问题有点晚了,但我偶然发现了一个类似的问题,但我想使用命名参数的dict而不是元组(因为如果我想修改参数来添加或删除一些,我不想重新构造元组,混乱的顺序可能非常容易,并导致bug...)。
我的解决方案是格式化查询字符串,将参数分解为几个参数,然后用这些新参数构造参数dict:
结果:
可以做得更好,但我找不到使用命名参数的dict而不是有序元组的解决方案。
23c0lvtd5#
如果你使用
Django 2.0 or 2.1
和Python 3.6
,这是正确的方法:参考:https://stackoverflow.com/a/23891759/2803344 https://docs.djangoproject.com/en/2.1/topics/db/sql/#passing-parameters-into-raw
bvuwiixz6#
如果您不想关心必须传递参数以完成查询字符串的方法,而只想调用
cursror.execute(query)
,那么这在某些用例中是可行的。另一种方式可以是:
omjgkv6w7#
另一个使用列表解析的简单解决方案:
piwo6bdm8#
虽然这个问题很古老。我分享我的解决方案,如果它可以帮助别人。
list_to_check = ['A', 'B'] cursor.execute("DELETE FROM foo.bar WHERE baz IN ({})".format(str(list_to_check)[1:-1])
使用
Python=3.6
进行测试xdnvmnnf9#
很简单:就用下面的队形
rules_id = [“9”,“10”]
“SELECT * FROM attendance_rules_staff WHERE id in(“+",“.join(map(str,rules_id))+”)”
",“.join(map(str,rules_id))