MySQL Connector/Python 发行说明
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))