問題描述
我知道如何將列表映射到字符串:
I know how to map a list to a string:
foostring = ",".join( map(str, list_of_ids) )
而且我知道我可以使用以下內(nèi)容將該字符串放入 IN 子句中:
And I know that I can use the following to get that string into an IN clause:
cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring))
我需要的是使用 MySQLDB 安全地完成同樣的事情(避免 SQL 注入).在上面的例子中,因為 foostring 沒有作為參數(shù)傳遞給 execute,所以它很容易受到攻擊.我還必須在 mysql 庫之外引用和轉(zhuǎn)義.
What I need is to accomplish the same thing SAFELY (avoiding SQL injection) using MySQLDB. In the above example because foostring is not passed as an argument to execute, it is vulnerable. I also have to quote and escape outside of the mysql library.
(有一個相關(guān)SO問題,但是那里列出的答案要么不適用于 MySQLDB,要么容易受到 SQL 注入的影響.)
(There is a related SO question, but the answers listed there either do not work for MySQLDB or are vulnerable to SQL injection.)
推薦答案
直接使用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注入.
That way you avoid having to quote yourself, and avoid all kinds of sql injection.
請注意,數(shù)據(jù) (list_of_ids
) 作為參數(shù)(不在查詢文本中)直接進(jìn)入 mysql 的驅(qū)動程序,因此沒有注入.您可以在字符串中保留您想要的任何字符,無需刪除或引用字符.
Note that the data (list_of_ids
) is going directly to mysql's driver, as a parameter (not in the query text) so there is no injection. You can leave any chars you want in the string, no need to remove or quote chars.
這篇關(guān)于內(nèi)爆一個在 python MySQLDB IN 子句中使用的列表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!