Python – mysqlDB,sqlite结果作为字典

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

内容简介:代码日志版权声明:翻译自: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结果作为字典》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Algorithm Design

Algorithm Design

Jon Kleinberg、Éva Tardos / Addison-Wesley / 2005-3-26 / USD 144.20

Algorithm Design introduces algorithms by looking at the real-world problems that motivate them. The book teaches students a range of design and analysis techniques for problems that arise in compu......一起来看看 《Algorithm Design》 这本书的介绍吧!

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

在线压缩/解压 JS 代码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具