使用 python sqlite3 — 从 sqlite 表中选择列表中的 rowid数据库API 2.0
以下有效:
>>> 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 列表,而不必先将其格式化为字符串?
The following works:
>>> cursor.execute("select * from sqlitetable where rowid in (2,3);")
The following doesn't:
>>> cursor.execute("select * from sqlitetable where rowid in (?) ", [[2,3]] )
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
Is there a way to pass in a python list without having to format it into a string first ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不幸的是没有。每个值都必须有自己的参数标记 (
?
)。由于参数列表(大概)可以具有任意长度,因此您必须使用字符串格式来构建正确数量的参数标记。幸运的是,这并不难:
Unfortunately not. Each value must be given its own parameter mark (
?
).Since the argument list can (presumably) have arbitrary length, you must use string formating to build the correct number of parameter marks. Happily, that isn't so hard:
在 Python 3.6 中,您还可以使用 f 字符串构建查询:
In Python 3.6 you can also build queries with the f strings:
如前所述,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
As described before, SQLite supports only a limited set of types natively.
To use other Python types with SQLite, you must adapt them to one of the sqlite3 module’s supported types for SQLite: one of NoneType, int, float, str, bytes.
https://docs.python.org/3.6/library/sqlite3.html#using-adapters-to-store-additional-python-types-in-sqlite-databases
我需要在查询中包含多个
IN
子句以及其他命名参数,并提出了一种可以让我这样做的辅助方法:它使用此辅助方法:
I needed to include more than one
IN
clause with a query along with other named parameters and came up with a helper method that would let me do:Which uses this helper method: