Python – mysqlDB,sqlite结果作为字典

栏目: Python · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/4147707/python-mysqldb-sqlite-result-as-dictionary

当我做某事时

sqlite.cursor.execute("SELECT * FROM foo")
result = sqlite.cursor.fetchone()

我想必须记住这些列似乎能够把它们取出来的顺序,例如

result[0] is id
result[1] is first_name

有没有办法返回字典?所以我可以使用结果[‘id’]或类似的?

编号列的问题是,如果您编写代码,则插入一列,您可能需要更改代码,例如first_name的result [1]现在可能是date_joined,因此必须更新所有代码…

David Beazley在他的Python Essential Reference中有一个很好的例子.

我手上没有这本书,但我认为他的例子是这样的:

def dict_gen(curs):
    ''' From Python Essential Reference by David Beazley
    '''
    import itertools
    field_names = [d[0].lower() for d in curs.description]
    while True:
        rows = curs.fetchmany()
        if not rows: return
        for row in rows:
            yield dict(itertools.izip(field_names, row))

样品用量:

>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute('create table test (col1,col2)')
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (1,'foo')")
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (2,'bar')")
<sqlite3.Cursor object at 0x011A96A0>
# `dict_gen` function code here
>>> [r for r in dict_gen(c.execute('select * from test'))]
[{'col2': u'foo', 'col1': 1}, {'col2': u'bar', 'col1': 2}]

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/4147707/python-mysqldb-sqlite-result-as-dictionary


以上所述就是小编给大家介绍的《Python – mysqlDB,sqlite结果作为字典》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

响应式Web设计

响应式Web设计

本·弗莱恩 (Ben Frain) / 奇舞团 / 人民邮电出版社 / 2017-2-1 / CNY 59.00

本书将当前Web 设计中热门的响应式设计技术与HTML5 和CSS3 结合起来,为读者全面深入地讲解了针对各种屏幕大小设计和开发现代网站的各种技术。书中不仅讨论了媒体查询、弹性布局、响应式图片,更将最新和最有用的HTML5 和CSS3 技术一并讲解,是学习最新Web 设计技术不可多得的佳作。一起来看看 《响应式Web设计》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

随机密码生成器
随机密码生成器

多种字符组合密码