从数据库删除数据

Python 中的数据库入门

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

从表中删除数据

  • 使用 delete() 语句完成
  • delete() 接受要删除数据的表作为参数
  • 使用 where() 子句选择要删除的行
  • 难以撤销,请谨慎!
Python 中的数据库入门

删除表中所有数据

from sqlalchemy import delete

stmt = select([func.count(extra_employees.columns.id)])
connection.execute(stmt).scalar()
3
delete_stmt = delete(extra_employees)

result_proxy = connection.execute(delete_stmt) result_proxy.rowcount
3
Python 中的数据库入门

删除特定行

  • 构建一个 where() 子句,选出要删除的所有记录
Python 中的数据库入门

删除特定行

stmt = delete(employees).where(employees.columns.id == 3)

result_proxy = connection.execute(stmt) result_proxy.rowcount
1
Python 中的数据库入门

彻底删除一张表

  • 使用表的 drop() 方法
  • 接受 engine 作为参数,以便知道从哪里删除表
  • 在重启 Python 进程前,不会从 metadata 中移除
Python 中的数据库入门

删除一张表

extra_employees.drop(engine)

print(extra_employees.exists(engine))
False
Python 中的数据库入门

删除所有表

  • 在 MetaData 上使用 drop_all() 方法
Python 中的数据库入门

删除所有表

metadata.drop_all(engine)

engine.table_names()
[]
Python 中的数据库入门

Passons à la pratique !

Python 中的数据库入门

Preparing Video For Download...