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