python mysql.connector DictCursor? [英] python mysql.connector DictCursor?

查看:334
本文介绍了python mysql.connector DictCursor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python mysqldb中,我可以这样将游标声明为字典游标:

In Python mysqldb I could declare a cursor as a dictionary cursor like this:

cursor = db.cursor(MySQLdb.cursors.DictCursor) 

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

This would enable me to reference columns in the cursor loop by name like this:

for row in cursor:   # Using the cursor as iterator 
    city = row["city"]
    state = row["state"]

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

Is it possible to create a dictionary cursor using this MySQL connector? http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html

他们的示例仅返回一个元组.

Their example only returns a tuple.

我想MySQL的创建者最终会为我们做到这一点?

I imagine the creators of MySQL would eventually do this for us?

推荐答案

可能的解决方案包括将MySQLCursor类的子类化,如下所示:

A possible solution involves subclassing the MySQLCursor class like this:

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.

Now the _row_to_python() method returns a dictionary instead of a tuple.

我在mysql论坛上找到了这个,我相信它是由mysql开发人员自己发布的.我希望他们有朝一日将其添加到mysql连接器包中.

I found this on the mysql forum, and I believe it was posted by the mysql developers themselves. I hope they add it to the mysql connector package some day.

我对此进行了测试,并且确实有效.

I tested this and it does work.

更新:如下面的Karl M.W所提到的那样,在mysql.connector的v2中不再需要此子类. mysql.connector已更新,现在您可以使用以下选项启用字典光标.

UPDATE: As mentioned below by Karl M.W... this subclass is no longer needed in v2 of the mysql.connector. The mysql.connector has been updated and now you can use the following option to enable a dictionary cursor.

cursor = db.cursor(dictionary=True)

这篇关于python mysql.connector DictCursor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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