【问题标题】:MySQL fetchall() - how to get data inside a dict rather than inside a tupleMySQL fetchall() - 如何在字典中而不是在元组中获取数据
【发布时间】:2015-03-12 21:46:48
【问题描述】:

我有一个表,其列为idcol1col2col3。我就是这样执行查询的。

cur.execute(query)
row = cur.fetchall()

我能否在dict 中获取row 的数据,即我想将此结果作为结果传递给api

cur.fetchall() 将产生以下格式的结果((id,col1,col2,col3),(id,col1,col2,col3),(id,col1,col2,col3))

我能得到结果吗

[
   {id:value,col1:value,col2:value,col3:value},
   {id:value,col1:value,col2:value,col3:value},
   {id:value,col1:value,col2:value,col3:value}
]

我知道这个概念,我可以循环fetchall(),并使用字典概念获取值,即

rows = cursor.fetchall()
for row in rows:
   id = row['id']
   col1 = row['col1']
   and so on...

我可以将rows 作为字典传递吗?

【问题讨论】:

    标签: python mysql dictionary


    【解决方案1】:

    如果您使用mysql-connector库连接数据库,简单的方法是在cursor函数中将dictionary设置为True

    db = connector.connect(**config)
    
    cursor = db.cursor(dictionary=True)
    

    【讨论】:

    • TypeError: cursor() got an unexpected keyword argument 'dictionary'
    • @caram 正如您已经知道的那样,那是因为您使用的是MySQLdb 连接器,此解决方案适用于mysql-connector
    【解决方案2】:

    您需要使用cursor.description“压缩”结果值:

    columns = [col[0] for col in cursor.description]
    rows = [dict(zip(columns, row)) for row in cursor.fetchall()]
    

    【讨论】:

    • 这就像循环 fetchall() 并创建一个字典一样,这很耗时。有什么直接的解决办法吗?
    • @user1162512 恐怕没有什么内置的。每当我需要时,我一直在使用这种方法。作为一种替代方法,您可以使用 ORM 来隐藏它的工作方式,但会给您模型对象以“点”访问字段..
    • @user1162512 顺便说一句,据我回忆,Django 使用相同的方法将模型字段与查询结果匹配。
    • 我一直是 Django 的狂热用户并且知道 Django 中的这个特性,但不知道它是如何工作的,因此想知道原始 MySQL 的相同之处。非常感谢:)
    • @user1162512 是的,还有information_schema.columns用过,见github.com/django/django/blob/…
    【解决方案3】:

    最简单的方法是使用DictCursor

    import MySQLdb
    ...
    cursor = db.cursor(MySQLdb.cursors.DictCursor)
    

    您还可以通过将cursor_class 参数传递给connect 来为db 生成的所有游标设置此项

    不同类型游标的文档在这里:https://mysqlclient.readthedocs.io/user_guide.html#using-and-extending

    【讨论】:

    • 太好了,恕我直言,这应该是公认的答案。
    【解决方案4】:

    我已经修改了一些 alecxe 的答案以压缩光标循环内的每一行。如果您有一个大表可能会有所帮助,因此您不会将所有行都保存在内存中。

    cursor = db.execute_sql("select * from something")
    columns = [col[0] for col in cursor.description]
    for row in cursor.fetchall():
        row = dict(zip(columns, row))
        print(row)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-10
      • 2017-07-16
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      相关资源
      最近更新 更多