文件首頁
MySQL Connector/Python 開發者指南
相關文件 下載本手冊
PDF (美式信紙) - 0.7Mb
PDF (A4) - 0.7Mb


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