從資料表篩選資料 - 基礎
已經連線到資料庫,現在來練習如何在查詢中做篩選!
影片中提到,where() 子句可用來篩選陳述式所回傳的資料。例如,若要從 census 資料表選取性別為女性(或 'F')的所有紀錄,可以這麼做:
select([census]).where(census.columns.sex == 'F')
除了 ==,你也可以在 where() 子句中使用幾乎所有 Python 比較運算子(例如 <=、!= 等)。
本練習屬於課程
Python 資料庫入門
練習說明
- 將
census以清單形式傳給select(),以選取census資料表中的所有紀錄。 - 在
stmt後加入where子句,只回傳state為'New York'的紀錄。 - 以
connection的.execute()執行陳述式stmt,並用.fetchall()取回結果。 - 走訪
results,對每筆紀錄印出age、sex與pop2000欄位。例如,可以用result.age印出result的age。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a select query: stmt
stmt = ____
# Add a where clause to filter the results to only those for New York : stmt_filtered
stmt = stmt.____
# Execute the query to retrieve all the data returned: results
results = ____
# Loop over the results and print the age, sex, and pop2000
for ___ in ____:
print(result.age, ____, ____)