10.6.4 cursor.MySQLCursorDict类

该类MySQLCursorDict继承自 MySQLCursor. 此类自 Connector/Python 2.0.0 起可用。

游标将MySQLCursorDict每一行作为字典返回。每个字典对象的键是 MySQL 结果的列名。

例子:

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']

前面的代码产生如下输出:

Countries in Europe:
* Albania
* Andorra
* Austria
* Belgium
* Bulgaria
...

format()将字典传递给如下 可能很方便 :

cursor.execute("SELECT Name, Population FROM country WHERE Continent = 'Europe'")

print("Countries in Europe with population:")
for row in cursor:
    print("* {Name}: {Population}".format(**row))