3

我试图弄清楚如何正确使用 WHERE _ IN _语句

定义:

c.execute('''CREATE TABLE IF NOT EXISTS tab (
    _id integer PRIMARY KEY AUTOINCREMENT,
    obj text NOT NULL
    ) ;''')

我正在尝试做这样的事情:

list_of_vars=['foo','bar']
statement="SELECT * FROM tab WHERE obj IN (?)"
c.execute(statement,"'"+"','".join(list_of_vars)+"'")

或者,我也试过这个,它直接评估为上述

statement="SELECT * FROM tab WHERE obj IN (?)"
c.execute(statement,"'foo','bar'")

我得到的错误是:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 9 supplied

这给了我一个错误。当我这样做时,它可以工作,但不建议这样做,因为它容易受到 SQL 注入攻击。

statement="SELECT * FROM tab WHERE obj IN ("+"'"+"','".join(statement)+"'"+")
4

2 回答 2

10

您需要创建足够的参数来匹配您的变量列表:

statement = "SELECT * FROM tab WHERE obj IN ({0})".format(', '.join(['?'] * len(list_of_vars)))
c.execute(statement, list_of_vars)

请注意,您list_of_vars作为参数值列表传入。使用', '.join()我们生成一个?用逗号分隔的字符串,然后将.format()其插入到语句中。

For a long list of variables, it may be more efficient to use a temporary table to hold those values, then use a JOIN against the temporary table rather than an IN clause with bind parameters.

于 2013-01-09T19:59:21.657 回答
1

FYI, pymysql with MySQL user.

query ="SELECT * FROM tab WHERE obj IN %s"
cursor.execute(query, (['foo','bar'],))

same as

cursor.execute(query, (list_of_var,)) 

I'm not sure about sqlite3, this may work,

query ="SELECT * FROM tab WHERE obj IN ?"
cursor.execute(query, (['foo','bar'],)) 
or
cursor.execute(query, (list_of_vars,))  
于 2021-07-19T07:11:39.207 回答