MySQL 连接器/Python 开发人员指南 / 第 10 章连接器/Python API 参考 / 10.6 cursor.MySQLCursor 的子类 /
10.6.4 cursor.MySQLCursorDict类
该类MySQLCursorDict
继承自
MySQLCursor
. 此类自 Connector/Python 2.0.0 起可用。
游标将MySQLCursorDict
每一行作为字典返回。每个字典对象的键是 MySQL 结果的列名。
例子:
Press CTRL+C to copycnx = 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']
前面的代码产生如下输出:
Press CTRL+C to copyCountries in Europe: * Albania * Andorra * Austria * Belgium * Bulgaria ...
format()
将字典传递给如下
可能很方便
:
Press CTRL+C to copycursor.execute("SELECT Name, Population FROM country WHERE Continent = 'Europe'") print("Countries in Europe with population:") for row in cursor: print("* {Name}: {Population}".format(**row))