從資料庫刪除資料

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 行程前,不會從中繼資料中移除
Python 資料庫入門

刪除資料表

extra_employees.drop(engine)

print(extra_employees.exists(engine))
False
Python 資料庫入門

刪除所有資料表

  • 在 MetaData 上使用 drop_all() 方法
Python 資料庫入門

刪除所有資料表

metadata.drop_all(engine)

engine.table_names()
[]
Python 資料庫入門

一起來練習吧!

Python 資料庫入門

Preparing Video For Download...