![](/img/trans.png)
[英]Select rows from one table where certain field is equal to a field in a row from another table, with Python and SQLite3
[英]Python3 + DB: “Select * from `table` where `field` IN (…) AND `field2` = '…'”
使用Python3和
cursor.execute(sql, {key1: val1, key2: val2})
語法,我想執行一個安全的(SQL注入證明)查詢,例如:
SELECT * FROM `table`
WHERE
a = %(fieldA)s AND b IN (%(fieldB)s)
基本上,我正在尋找這個問題的答案,但是要使用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
。
我仍然不明白為什么有些人聲稱在這種情況下我們必須使用元組,因為列表工作得很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.