การลบระเบียนที่ระบุ
การใช้ where() clause ช่วยให้กำหนดเป้าหมายของ delete statement ได้อย่างแม่นยำ เพื่อลบเฉพาะระเบียนที่ต้องการ ตัวอย่างเช่น Jason ลบแถวทั้งหมดในตาราง employees ที่มี id เป็น 3 ด้วย delete statement ต่อไปนี้:
delete(employees).where(employees.columns.id == 3)
ในแบบฝึกหัดนี้ จะลบแถว ทั้งหมด ที่มีค่า 'M' ในคอลัมน์ sex และค่า 36 ในคอลัมน์ age โดยโค้ดที่เตรียมไว้ให้ตอนต้นจะคำนวณจำนวนแถวทั้งหมดเหล่านี้ ซึ่งสำคัญมากที่ต้องตรวจสอบให้แน่ใจว่าจำนวนแถวที่ลบออกไปตรงกับค่าดังกล่าว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับฐานข้อมูล
คำแนะนำการฝึกหัด
- สร้าง
deletestatement เพื่อลบข้อมูลออกจากตารางcensusแล้วบันทึกไว้ในตัวแปรdelete_stmt - ต่อ
whereclause เข้ากับdelete_stmtโดยใช้and_เพื่อกรองแถวที่มีค่า'M'ในคอลัมน์sexและ ค่า36ในคอลัมน์age - รัน delete statement
- ส่งคำตอบเพื่อพิมพ์ค่า
rowcountของresultsพร้อมกับto_deleteซึ่งแสดงจำนวนแถวที่ควรถูกลบ ค่าทั้งสองควรตรงกัน ซึ่งเป็นการตรวจสอบความถูกต้องที่สำคัญ!
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Build a statement to count records using the sex column for Men ('M') age 36: count_stmt
count_stmt = select([func.count(census.columns.sex)]).where(
and_(census.columns.sex == 'M',
census.columns.age == 36)
)
# Execute the select statement and use the scalar() fetch method to save the record count
to_delete = connection.execute(count_stmt).scalar()
# Build a statement to delete records from the census table: delete_stmt
delete_stmt = ____
# Append a where clause to target Men ('M') age 36: delete_stmt
delete_stmt = delete_stmt.____(
____(census.columns.sex == ____,
____ == ____)
)
# Execute the statement: results
results = connection.execute(____)
# Print affected rowcount and to_delete record count, make sure they match
print(results.rowcount, to_delete)