删除特定记录
通过使用 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)