Xóa tất cả bản ghi khỏi một bảng
Không ít lần bạn sẽ cần làm trống một bảng để nạp lại dữ liệu. Bạn có thể làm điều này với câu lệnh delete chỉ cần truyền vào chính bảng đó. Ví dụ, trong video, Jason đã xóa bảng extra_employees bằng cách thực thi như sau:
delete_stmt = delete(extra_employees)
result_proxy = connection.execute(delete_stmt)
Hãy thật cẩn thận, vì thao tác xóa không thể hoàn tác!
Bài tập này là một phần của khóa học
Nhập môn Cơ sở dữ liệu với Python
Hướng dẫn bài tập
- Import
deletevàselecttừ sqlalchemy. - Tạo một câu lệnh
deleteđể xóa toàn bộ dữ liệu từ bảngcensus. Lưu vàodelete_stmt. - Thực thi
delete_stmtquaconnectionvà lưuresults. - Gửi câu trả lời để
selecttất cả các hàng còn lại từ bảngcensusvà in kết quả để xác nhận bảng đã trống!
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# 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())