刪除資料表中的所有紀錄
在實務上,你常常需要清空資料表的所有紀錄,才能重新載入資料。你可以使用只帶資料表作為引數的 delete 陳述式來達成。例如在影片中,Jason 透過下列方式刪除了 extra_employees 資料表:
delete_stmt = delete(extra_employees)
result_proxy = connection.execute(delete_stmt)
不過要特別小心,刪除操作無法復原!
本練習屬於課程
Python 資料庫入門
練習說明
- 從 sqlalchemy 匯入
delete與select。 - 建立一個
delete陳述式以移除census資料表中的所有資料,並將其儲存為delete_stmt。 - 透過
connection執行delete_stmt,並將結果儲存為results。 - 送出答案以
select出census資料表中所有剩餘列,並列印結果,確認資料表現在已經是空的!
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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())