python - MySQL fetchall() - 如何在字典中而不是在元组中获取数据

标签 python mysql dictionary

我有一个表,其列为 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 作为字典传递吗?

最佳答案

如果您使用mysql-connector 库连接到数据库,最简单的方法是将dictionary 设置为True inside 光标功能:

db = connector.connect(**config)

cursor = db.cursor(dictionary=True)

关于python - MySQL fetchall() - 如何在字典中而不是在元组中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29020839/

相关文章:

Python opencv 没有收到相机提要

python - 文件中的奇怪字符无声地中断 for 循环

sql - MySQL Select 查询存在 "IN"条件的问题

python - Python 字典是哈希表的一个例子吗?

python开始方法

python - 我无法让 OpenID 工作(openid.consumer.consumer.ProtocolError : Parameter next not in return_to URL)

java - Liferay Service Builder - 创建引用

php - 更新foreach中的数据

javascript - 下划线 : map through object (even if undefined)

python - 如何用字典中的值交换键?