【问题标题】:How do I query MySQL into a dictionary using Python?如何使用 Python 将 MySQL 查询到字典中?
【发布时间】:2020-04-19 16:32:08
【问题描述】:

我正在尝试将我的查询结果提取到 Python 中的字典中,但不太确定如何执行此操作。

我在光标配置中设置了 Dictionary=true 但这似乎没有按预期工作。

import mysql.connector as mariadb
#  DB VARIABLES
mariadb_connection = mariadb.connect(user='user', password='pass', database='mydb')
cursor = mariadb_connection.cursor(dictionary=True)

cursor.execute("SELECT id, name FROM songs")
rows = cursor.fetchall()
print(rows)
if isinstance(rows, dict):
    print("this IS a dictionary")

上面的代码不打印任何东西。

【问题讨论】:

    标签: python mysql python-3.x


    【解决方案1】:

    当您使用.fetchall() 时,您将检索多个结果,即使查询只有一个结果,它也会是list of all results


    使用dictionary=True 将为您提供dict 的列表,其字段名称如下

    [{'id': '123456', 'name': 'This is the supe song 1'},
     {'id': '456789', 'name': 'This is the supe song 2'},
     {'id': '789123', 'name': 'This is the supe song 3'}]
    

    没有dictionary=True,你只会得到一个元组形式的值列表

    [('123456', 'This is the supe song 1'),
     ('456789', 'This is the supe song 2'),
     ('789123', 'This is the supe song 3')]
    

    下面是True所以

    isinstance(rows, list) # True
    isinstance(rows[0], dict) # True
    

    【讨论】:

      【解决方案2】:

      如果您想获取字典,您需要决定将什么用作字典键。假设是第一个返回的字段,即id

      mariadb_connection = mariadb.connect(user='user', password='pass', database='mydb')
      cursor = mariadb_connection.cursor()
      cursor.execute("SELECT id, name FROM songs")
      rows = cursor.fetchall()
      dic = { t[0]: t[1:] for t in rows }
      

      当然,要使其正常工作,id 中的值必须是唯一的。

      【讨论】:

      • Id 列应该是字典的唯一索引。使用上面的代码,我得到一个“太多的值来解压(预期为 2)。在我的实际查询中,我有多个列,而不仅仅是 idname
      • 查看更改后的答案。顺便说一句,给出一个误导性的例子并不是获得正确答案的最佳方式。
      • 我无意误导,只是为了简化代码以将问题与代码的其余部分隔离开来。
      猜你喜欢
      • 2019-11-21
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多