How can I get dict from sqlite query?(如何从sqlite查询中获取dict?)
问题描述
db = sqlite.connect("test.sqlite")
res = db.execute("select * from table")
通过迭代,我得到与行对应的列表.
With iteration I get lists coresponding to the rows.
for row in res:
print row
我可以得到列的名称
col_name_list = [tuple[0] for tuple in res.description]
但是是否有一些函数或设置可以获取字典而不是列表?
But is there some function or setting to get dictionaries instead of list?
{'col1': 'value', 'col2': 'value'}
还是我必须自己做?
推荐答案
你可以使用 row_factory,如文档中的示例:
You could use row_factory, as in the example in the docs:
import sqlite3
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]
或遵循文档中此示例之后给出的建议:
or follow the advice that's given right after this example in the docs:
如果返回一个元组还不够并且您希望基于名称访问列,您应该考虑设置row_factory 到高度优化的sqlite3.Row 类型.行同时提供基于索引且不区分大小写基于名称的列访问几乎没有内存开销.它会可能比你自己的好自定义基于字典的方法或甚至是基于 db_row 的解决方案.
If returning a tuple doesn’t suffice and you want name-based access to columns, you should consider setting row_factory to the highly-optimized sqlite3.Row type. Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.
这是第二种解决方案的代码:
Here is the code for this second solution:
con.row_factory = sqlite3.Row
这篇关于如何从sqlite查询中获取dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从sqlite查询中获取dict?
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
