select from sqlite table where rowid in list使用python sqlite3 - DB-API 2.0

shyt4zoc  于 2023-08-06  发布在  SQLite
关注(0)|答案(4)|浏览(112)

以下工程:

>>> cursor.execute("select * from sqlitetable where rowid in (2,3);")

字符串
以下内容不适用:

>>> cursor.execute("select * from sqlitetable where rowid in (?) ", [[2,3]] )
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.


有没有一种方法可以传入一个python列表,而不必先将其格式化为字符串?

qxsslcnc

qxsslcnc1#

很遗憾没有每个值都必须有自己的参数标记(?)。由于参数列表可以(假定)具有任意长度,因此必须使用字符串格式来构建正确数量的参数标记。幸运的是,这并不难:

args=[2,3]
sql="select * from sqlitetable where rowid in ({seq})".format(
    seq=','.join(['?']*len(args)))

cursor.execute(sql, args)

字符串

lhcgjxsq

lhcgjxsq2#

在Python 3.6中,你也可以用f字符串构建查询:

args=[2, 3]
query = f"SELECT * FROM sqlitetable WHERE rowid in ({','.join(['?']*len(args))})"
cursor.execute(query, args)

字符串

rqdpfwrv

rqdpfwrv3#

SQLite本身只支持TEXT、INTEGER、真实的、BLOB和NULL类型。如果你想使用其他类型,你必须自己添加对它们的支持。detect_types参数和使用在模块级register_converter()函数中注册的自定义转换器使您可以轻松地完成此操作。
如前所述,SQLite本机仅支持有限的类型集。
要在SQLite中使用其他Python类型,必须使它们适应sqlite3模块支持的SQLite类型之一:NoneType、int、float、str、bytes之一。
https://docs.python.org/3.6/library/sqlite3.html#using-adapters-to-store-additional-python-types-in-sqlite-databases

wz1wpwve

wz1wpwve4#

我需要在查询中包含多个IN子句沿着其他命名参数,并提出了一个帮助方法,可以让我做到:

params = {'mn': 5, 'mx': 15}
in_a = sql_in([1,2,3], params, prefix='a')
in_b = sql_in([5,6,7], params, prefix='b')
query = (
    "SELECT rowid, name FROM tbl "
    "WHERE value BETWEEN :mn AND :mx"
    f" AND (alpha IN {in_a} OR beta IN {in_b})"
)
dbcon.execute(query, params)

字符串
它使用这个helper方法:

def sql_in(values, params, *, prefix='in'):
    """Generate an IN clause for SQLite using named placeholders.
    Given values=[1,2,3], will return:
        '(:in0,:in1,:in2)'
    after doing:
        params.update({'in0':1,'in1':2,'in2':3})
    If you're using this multiple times with a single dbcon.execute(),
    you need to give each one a distinct prefix, e.g.:
      params = {}
      in_a = sql_in([1,2,3], params, prefix='a')
      in_b = sql_in([5,6,7], params, prefix='b')
      dbcon.execute(f'SELECT * FROM tbl WHERE a IN {in_a} OR b IN {in_b}', params)
    """
    def inner():
        yield '('
        delim = ':'
        for i, val in enumerate(values):
            key = f'{prefix}{i}'
            assert key not in params
            params[key] = val
            yield delim
            yield key
            delim = ',:'
        yield ')'
    return ''.join(inner())

相关问题