开始使用免费开始使用

删除表中的所有记录

在实际工作中,您常常需要先清空一张表,再重新加载数据。您可以仅以表作为参数来构建一个 delete 语句来完成此操作。例如,在视频中,Jason 通过如下方式删除了表 extra_employees

delete_stmt = delete(extra_employees)
result_proxy = connection.execute(delete_stmt)

但请务必小心,一旦删除就无法恢复!

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • 从 sqlalchemy 导入 deleteselect
  • 构建一个 delete 语句以删除 census 表中的所有数据,并将其保存为 delete_stmt
  • 通过 connection 执行 delete_stmt,并将结果保存为 results
  • 提交答案时,selectcensus 表中所有剩余的行并打印结果,以确认该表现在已为空!

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import delete, select
from sqlalchemy import ____, ____

# Build a statement to empty the census table: stmt
delete_stmt = ____

# Execute the statement: results
results = ____

# Print affected rowcount
print(results.rowcount)

# Build a statement to select all records from the census table : select_stmt
select_stmt = select([census])

# Print the results of executing the statement to verify there are no rows
print(connection.execute(select_stmt).fetchall())
编辑并运行代码