雖然這個問題很舊,但我想留下回復,以防其他人也在尋找我想要的東西
當我們有很多參數(shù)或者想要使用命名參數(shù)時,接受的答案會變得混亂
經(jīng)過一些嘗試
ids = [5, 3, ...] # id列表 cursor.execute(''' SELECT ... WHERE id IN %(ids)s AND created_at > %(start_dt)s ''', { 'ids': tuple(ids), 'start_dt': '2019-10-31 00:00:00' })
在python2.7
和pymysql==0.7.11
下測試通過
直接使用list_of_ids
:
format_strings = ','.join(['%s'] * len(list_of_ids)) cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings, tuple(list_of_ids))
這樣可以避免自己引用,也避免了各種SQL注入問題。
請注意,數(shù)據(jù)(list_of_ids
)直接傳遞給mysql的驅動程序作為參數(shù)(而不是在查詢文本中),因此沒有注入問題。您可以在字符串中保留任何字符,無需刪除或引用字符。