特定のレコードを削除する
where() 句を使うと、delete 文で特定のレコードだけを削除できます。たとえば、Jason は次の削除文で、employees テーブルから id が 3 のすべての行を削除しました。
delete(employees).where(employees.columns.id == 3)
ここでは、sex 列が 'M'、かつ age 列が 36 の行をすべて削除します。先頭のコードでは、これらの行の合計数を計算しています。実際に削除される行数と一致していることを必ず確認してください。
この演習はコースの一部です
Pythonで学ぶデータベース入門
演習の手順
censusテーブルからデータを削除するdelete文を作成し、delete_stmtとして保存します。delete_stmtにwhere句を追加し、その中でand_を使って、sex列が'M'であり かつage列が36の行に絞り込みます。- 削除文を実行します。
- Submit Answer を行い、
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)