ลบข้อมูลทั้งหมดออกจากตาราง
บางครั้งคุณจำเป็นต้องล้างข้อมูลทั้งหมดออกจากตาราง เพื่อนำข้อมูลชุดใหม่เข้ามาแทน โดยใช้คำสั่ง delete พร้อมระบุชื่อตารางเป็น argument ตัวอย่างเช่น ในวิดีโอ Jason ลบข้อมูลทั้งหมดออกจากตาราง extra_employees ด้วยโค้ดต่อไปนี้:
delete_stmt = delete(extra_employees)
result_proxy = connection.execute(delete_stmt)
อย่างไรก็ตาม โปรดใช้ความระมัดระวัง เพราะการลบข้อมูลไม่สามารถย้อนกลับได้!
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับฐานข้อมูล
คำแนะนำการฝึกหัด
- Import
deleteและselectจาก sqlalchemy - สร้างคำสั่ง
deleteเพื่อลบข้อมูลทั้งหมดออกจากตารางcensusแล้วบันทึกไว้ในตัวแปรdelete_stmt - รัน
delete_stmtผ่านconnectionและบันทึกผลลัพธ์ไว้ใน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())