提取地图的Python,MySQL和游标 [英] Python, MySQL and cursors that fetch maps

查看:50
本文介绍了提取地图的Python,MySQL和游标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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.

  • 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 (为什么?)请使用

  • 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和游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆