【问题标题】:Python - mysqlDB, sqlite result as dictionaryPython - mysqlDB,sqlite 结果作为字典
【发布时间】:2010-11-10 18:23:21
【问题描述】:

当我做某事时

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

我认为必须记住列似乎能够提取它们的顺序,例如

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

有没有办法返回字典?所以我可以改用 result['id'] 或类似的?

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

【问题讨论】:

标签: python mysql sqlite dictionary dataformat


【解决方案1】:
import MySQLdb
dbConn = MySQLdb.connect(host='xyz', user='xyz', passwd='xyz', db='xyz')
dictCursor = dbConn.cursor(MySQLdb.cursors.DictCursor)
dictCursor.execute("SELECT a,b,c FROM table_xyz")
resultSet = dictCursor.fetchall()
for row in resultSet:
    print row['a']
dictCursor.close
dbConn.close()

【讨论】:

  • 有没有办法将DictCursor 检索到的行添加到set() 而不会遇到TypeError: unhashable type: 'dict'
【解决方案2】:

在 mysqlDB 中执行此操作只需将以下内容添加到连接函数调用中

cursorclass = MySQLdb.cursors.DictCursor

【讨论】:

    【解决方案3】:

    你可以很容易地做到这一点。对于 SQLite:my_connection.row_factory = sqlite3.Row

    查看 python 文档:http://docs.python.org/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index

    更新:

    Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sqlite3
    >>> conn = sqlite3.connect(':memory:')
    >>> conn.row_factory = sqlite3.Row
    >>> c = conn.cursor()
    >>> c.execute('create table test (col1,col2)')
    <sqlite3.Cursor object at 0x1004bb298>
    >>> c.execute("insert into test values (1,'foo')")
    <sqlite3.Cursor object at 0x1004bb298>
    >>> c.execute("insert into test values (2,'bar')")
    <sqlite3.Cursor object at 0x1004bb298>
    >>> for i in c.execute('select * from test'): print i['col1'], i['col2']
    ... 
    1 foo
    2 bar
    

    【讨论】:

    • 感谢@Adam 提供交互式示例。
    【解决方案4】:

    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}]
    

    【讨论】:

      【解决方案5】:

      可以将 sqlite3.Row 实例转换为 dict - 将结果转储为 json 非常方便

      >>> csr = conn.cursor()
      >>> csr.row_factory = sqlite3.Row
      >>> csr.execute('select col1, col2 from test')
      >>> json.dumps(dict(result=[dict(r) for r in csr.fetchall()]))
      

      【讨论】:

      • 这给了我一个dictionary update sequence element #0 has length 15; 2 is required
      猜你喜欢
      • 2011-01-11
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多