เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ลบข้อมูลทั้งหมดออกจากตาราง

บางครั้งคุณจำเป็นต้องล้างข้อมูลทั้งหมดออกจากตาราง เพื่อนำข้อมูลชุดใหม่เข้ามาแทน โดยใช้คำสั่ง 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())
แก้ไขและรันโค้ด