處理 ResultSet
回顧 ResultProxy 與 ResultSet 的差異:
- ResultProxy:由
.execute()方法回傳的物件。它可以用多種方式來取得查詢回傳的資料。 - ResultSet:在 ResultProxy 上使用
.fetchall()這類 fetch 方法後,實際取得的查詢資料。
將 ResultSet 與 ResultProxy 分開,能讓我們依需求擷取多或少的資料。
取得 ResultSet 之後,你可以用 Python 以欄位名稱或清單索引的方式存取其中所有資料。例如,你可以用 results[0] 取得結果的第一列。接著把那第一列指定給變數 first_row,就能用 first_row[0] 取得第一欄的資料,或用欄位名稱,例如 first_row['column_name']。現在就用你在前一個練習中從 census 資料表取得的 ResultSet 來練習這些操作。它已存放在變數 results 中。開始吧!
本練習屬於課程
Python 資料庫入門
練習說明
- 取出
results的第一列,指定給變數first_row。 - 列印
first_row第一欄的值。 - 列印
first_row中'state'欄位的值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Get the first row of the results by using an index: first_row
first_row = ____
# Print the first row of the results
print(first_row)
# Print the first column of the first row by accessing it by its index
print(____)
# Print the 'state' column of the first row by using its name
print(____)