简体   繁体   English

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

[英]select from sqlite table where rowid in list using python sqlite3 — DB-API 2.0

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 ? 有没有办法传入python列表而不必先将其格式化为字符串?

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: 令人高兴的是,这并不是那么难:

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

cursor.execute(sql, args)

In Python 3.6 you can also build queries with the f strings: 在Python 3.6中,您还可以使用f字符串构建查询:

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

SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. SQLite本身仅支持TEXT,INTEGER,REAL,BLOB和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. detect_types参数和使用模块级register_converter()函数注册的自定义转换器允许您轻松地执行此操作。

As described before, SQLite supports only a limited set of types natively. 如前所述,SQLite本身仅支持一组有限的类型。

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. 要在SQLite中使用其他Python类型,必须使它们适应SQLite的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 https://docs.python.org/3.6/library/sqlite3.html#using-adapters-to-store-additional-python-types-in-sqlite-databases

Let's ids_list be the list of desired row ids, a simple solution would be: ids_list成为所需行ID的列表,一个简单的解决方案是:

sql = "SELECT * FROM sqlitetable WHERE rowid IN {}".format(str(tuple(ids_list)
cursor.execute(sql)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM