首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python mysql.connector DictCursor?

python mysql.connector DictCursor?
EN

Stack Overflow用户
提问于 2014-03-31 18:55:49
回答 4查看 53.5K关注 0票数 30

在Python mysqldb中,我可以将游标声明为字典游标,如下所示:

代码语言:javascript
运行
复制
cursor = db.cursor(MySQLdb.cursors.DictCursor) 

这将使我能够按名称引用cursor循环中的列,如下所示:

代码语言:javascript
运行
复制
for row in cursor:   # Using the cursor as iterator 
    city = row["city"]
    state = row["state"]

是否可以使用此MySQL连接器创建字典游标?http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html

他们的例子只返回一个元组。

我想,MySQL的创建者最终会为我们这样做吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-04-04 04:13:28

一个可能的解决方案是像这样对MySQLCursor类进行子类划分:

代码语言:javascript
运行
复制
class MySQLCursorDict(mysql.connector.cursor.MySQLCursor):
    def _row_to_python(self, rowdata, desc=None):
        row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
        if row:
            return dict(zip(self.column_names, row))
        return None

db = mysql.connector.connect(user='root', database='test')

cursor = db.cursor(cursor_class=MySQLCursorDict)

现在,_row_to_python()方法返回一个dictionary而不是一个tuple

我在mysql论坛上找到了这个,我相信它是mysql开发人员自己发布的。我希望有一天他们会把它添加到mysql连接器包中。

我测试过这个,它确实有效。

更新:如下所述卡尔·M.W.在v2 of mysql.connector中不再需要这个子类。mysql.connector已经更新,现在可以使用以下选项启用字典游标。

代码语言:javascript
运行
复制
cursor = db.cursor(dictionary=True)
票数 18
EN

Stack Overflow用户

发布于 2014-12-15 19:55:21

此示例工作如下:

代码语言:javascript
运行
复制
cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']

请记住,在本例中,'Name'是特定于所引用数据库的列名的。

此外,如果您想使用存储过程,请执行以下操作:

代码语言:javascript
运行
复制
cursor.callproc(stored_procedure_name, args)
result = []
for recordset in cursor.stored_results():
    for row in recordset:
        result.append(dict(zip(recordset.column_names,row)))

其中,stored_procedure_name是要使用的存储过程的名称,而args是该存储过程的参数列表(如果没有要传递的参数,则该字段与[]一样为空)。

以下是MySQL文档中的一个示例:http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

票数 10
EN

Stack Overflow用户

发布于 2017-09-18 17:56:49

使用Python3.6.2和MySQLdb版本1.3.10,我可以使用:

代码语言:javascript
运行
复制
import MySQLdb
import MySQLdb.cursors

...

conn = MySQLdb.connect(host='...', 
                       <connection info>, 
                       cursorclass=MySQLdb.cursors.DictCursor)

try:
    with conn.cursor() as cursor:
        query = '<SQL>'
        data = cursor.fetchall()
        for record in data:
            ... record['<field name>'] ...

finally:
    conn.close()

我使用的是PyCharm,只需深入研究MySQLdb模块connections.py和cursors.py。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22769873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档