30

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

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

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

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 的创造者最终会为我们做这件事吗?

4

5 回答 5

32

根据这篇文章,可以通过将 'dictionary=True' 传递给游标构造函数: http: //dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

所以我尝试了:

cnx = mysql.connector.connect(database='bananas')
cursor = cnx.cursor(dictionary=True)

并得到: TypeError: cursor() got an unexpected keyword argument 'dictionary'

我试过了:

cnx = mysql.connector.connect(database='bananas')
cursor = cnx.cursor(named_tuple=True)

并得到: TypeError: cursor() got an unexpected keyword argument 'named_tuple'

我也试过这个:cursor = MySQLCursorDict(cnx)

但无济于事。显然,我在这里使用了错误的版本,我怀疑我们只需要耐心等待,因为http://downloads.mysql.com/docs/connector-python-relnotes-en.a4.pdf上的文档表明这些新功能是在写作时处于 alpha 阶段。

于 2014-08-05T20:50:35.053 回答
17

一个可能的解决方案包括MySQLCursor像这样子类化类:

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()方法返回 adictionary而不是 a tuple

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

我对此进行了测试,它确实有效。

更新:正如 Karl MW 在下面提到的 .. 在 mysql.connector 的 v2 中不再需要这个子类。mysql.connector 已更新,现在您可以使用以下选项启用字典游标。

cursor = db.cursor(dictionary=True)
于 2014-04-04T04:13:28.763 回答
10

这个例子有效:

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'特定于所引用数据库的列名。

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

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)))

wherestored_procedure_name是要使用的存储过程的名称,并且args是该存储过程的参数列表(将此字段留空,就像[]没有要传入的参数一样)。

MySQL这是此处找到的文档中的一个示例:http: //dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

于 2014-12-15T19:55:21.217 回答
8

使用 Python 3.6.2 和 MySQLdb 1.3.10 版,我可以使用它:

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。

于 2017-09-18T17:56:49.680 回答
0

我在默认游标返回没有列名的元组时遇到了同样的问题。

答案在这里:

在 MYSQL_CURSORCLASS 中使用 MySQLdb.cursors.DictCursor 时出错

app.config["MYSQL_CURSORCLASS"] = "DictCursor"

于 2022-02-24T21:18:43.140 回答