我有一个表,其列为 id
、col1
、col2
、col3
。我以这种方式执行了查询。
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/