问题描述
在MySQL数据库连接上执行查询语句后,我执行:
After executing a query statement on a MySQL database connection, I perform:
rows = cursor.fetchall()
这给出了一个数组数组.我想要一个字典数组,其中每个字典从表的请求列名称中获取其键,并关联表中的值.
This gives an array of arrays. I'd like to have an array of dictionaries, where each dictionary takes its keys from the requested column names of my table and associates the values from the table.
我该怎么做?
推荐答案
好吧,您忘了提到您使用的是哪个mysql库.
Well, you forgot to mention which mysql library you're using.
-
如果使用 oursql (我建议,这肯定是最好的),使用我们的SQL
DictCursor
.示例:
If using oursql (which I recommend, it is certainly the best one), use oursql's
DictCursor
. Example:
conn = oursql.connect(...)
curs = conn.cursor(oursql.DictCursor)
如果使用 MySQLdb (为什么?)请使用 MySQLdb的DictCursor
.示例:
If using MySQLdb (why?) Use MySQLdb's DictCursor
. Example:
conn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor)
curs = conn.cursor()
这样做将为您提供一个游标,该游标返回每一行的字典.请记住,查询中不要包含重复的行名.
Doing that will give you a cursor that returns dicts for each row. Remember to not have duplicate rownames in your query.
这篇关于提取地图的Python,MySQL和游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!