使用python sqlite3-DB-API 2.0从列表中rowid所在的sqlite表中选择

2024-05-15 21:06:05 发布

您现在位置:Python中文网/ 问答频道 /正文

以下工作:

>>> 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列表,而不必先将其格式化为字符串?


Tags: infromexecuteparameter情况errorwhereselect
3条回答

SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If you want to use other types you must add support for them yourself. The detect_types parameter and the using custom converters registered with the module-level register_converter() function allow you to easily do that.

如前所述,SQLite本机只支持有限的类型集。

要将其他Python类型与SQLite一起使用,必须使它们适应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

在Python3.6中,还可以使用f字符串构建查询:

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

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

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

cursor.execute(sql, args)

相关问题 更多 >