【问题标题】:Python3 + DB: "Select * from `table` where `field` IN (...) AND `field2` = '...'"Python3 + DB:“从 `table` 中选择 *,其中 `field` IN (...) AND `field2` = '...'”
【发布时间】:2019-07-05 00:31:04
【问题描述】:

使用 Python3 和

cursor.execute(sql, {key1: val1, key2: val2})

语法,我想执行一个安全的(SQL-injection-proof)查询,例如:

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'})

?

【问题讨论】:

    标签: python mysql sql python-3.x mysql-python


    【解决方案1】:

    好的,我想我刚刚发现了:

    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

    我仍然不明白为什么有些人声称在这种情况下我们必须使用元组,因为列表工作得非常好。

    【讨论】:

      猜你喜欢
      • 2011-04-06
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 2020-12-05
      • 2013-09-17
      • 2010-11-28
      相关资源
      最近更新 更多