刪除特定記錄
使用 where() 子句,你可以讓 delete 敘述只移除特定記錄。舉例來說,Jason 以以下刪除敘述刪除了 employees 資料表中 id 為 3 的所有列:
delete(employees).where(employees.columns.id == 3)
在這裡,你將刪除所有在 sex 欄位為 'M',且在 age 欄位為 36 的列。我們在開頭已提供用來計算這些列總數的程式碼。請務必確認你實際刪除的列數與此數字相同。
本練習屬於課程
Python 資料庫入門
練習說明
- 建立一個
delete敘述,從census資料表移除資料。將其儲存為delete_stmt。 - 在
delete_stmt後串接一個where子句,內含and_,用來篩選sex欄位為'M'且age欄位為36的列(兩個條件必須同時成立)。 - 執行這個刪除敘述。
- 送出答案以列印
results的rowcount,以及to_delete(應被刪除的列數)。兩者應該一致,這是很重要的檢核!
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Build a statement to count records using the sex column for Men ('M') age 36: count_stmt
count_stmt = select([func.count(census.columns.sex)]).where(
and_(census.columns.sex == 'M',
census.columns.age == 36)
)
# Execute the select statement and use the scalar() fetch method to save the record count
to_delete = connection.execute(count_stmt).scalar()
# Build a statement to delete records from the census table: delete_stmt
delete_stmt = ____
# Append a where clause to target Men ('M') age 36: delete_stmt
delete_stmt = delete_stmt.____(
____(census.columns.sex == ____,
____ == ____)
)
# Execute the statement: results
results = connection.execute(____)
# Print affected rowcount and to_delete record count, make sure they match
print(results.rowcount, to_delete)