使用Python sqlite3从SQLite表中选择rowid在列表中的记录

41 投票
4 回答
30403 浏览
提问于 2025-04-16 16:18

下面这个是可以正常工作的:

>>> 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列表,而不需要先把它转换成字符串呢?

4 个回答

0

SQLite 只支持几种基本的数据类型,分别是文本(TEXT)、整数(INTEGER)、浮点数(REAL)、二进制数据(BLOB)和空值(NULL)。如果你想使用其他类型的数据,就需要自己添加支持。通过设置 detect_types 参数和使用模块级的 register_converter() 函数注册自定义转换器,你可以很方便地做到这一点。

正如之前提到的,SQLite 原生只支持有限的数据类型。

如果你想在 SQLite 中使用其他 Python 数据类型,就必须把它们转换成 sqlite3 模块支持的类型之一:也就是 NoneType(空类型)、int(整数)、float(浮点数)、str(字符串)和 bytes(字节)。

https://docs.python.org/3.6/library/sqlite3.html#using-adapters-to-store-additional-python-types-in-sqlite-databases

16

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

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

很遗憾,不能这样做。每个值都必须单独用一个参数标记(?)来表示。因为参数的数量可以是任意的,所以你需要用字符串格式化的方法来生成正确数量的参数标记。幸运的是,这并不难:

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

cursor.execute(sql, args)

撰写回答