การอัปเดตข้อมูลในตาราง

Python เบื้องต้นสำหรับฐานข้อมูล

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

การอัปเดตข้อมูลในตาราง

  • ใช้คำสั่ง update()
  • คล้ายกับ insert() แต่มี where clause เพิ่มเติมเพื่อระบุแถวที่ต้องการอัปเดต
  • กำหนดค่าที่ต้องการอัปเดตด้วย values() ในรูปแบบ column=value
Python เบื้องต้นสำหรับฐานข้อมูล

การอัปเดตแถวเดียว

from sqlalchemy import update

stmt = update(employees) stmt = stmt.where(employees.columns.id == 3) stmt = stmt.values(active=True)
result_proxy = connection.execute(stmt) print(result_proxy.rowcount)
1
Python เบื้องต้นสำหรับฐานข้อมูล

การอัปเดตหลายแถว

  • สร้าง where clause เพื่อเลือกทุกแถวที่ต้องการอัปเดต
Python เบื้องต้นสำหรับฐานข้อมูล

การแทรกหลายแถว

stmt = update(employees)
stmt = stmt.where(employees.columns.active == True)

stmt = stmt.values(active=False, salary=0.00)
result_proxy = connection.execute(stmt) print(result_proxy.rowcount)
3
Python เบื้องต้นสำหรับฐานข้อมูล

Correlated updates

new_salary = select([employees.columns.salary])
new_salary = new_salary.order_by(
    desc(employees.columns.salary))
new_salary = new_salary.limit(1)

stmt = update(employees)
stmt = stmt.values(salary=new_salary)
result_proxy = connection.execute(stmt)
print(result_proxy.rowcount)
3
Python เบื้องต้นสำหรับฐานข้อมูล

Correlated updates

  • ใช้คำสั่ง select() เพื่อค้นหาค่าที่จะอัปเดตในคอลัมน์
  • มักใช้เพื่ออัปเดตข้อมูลให้เป็นค่าสูงสุด หรือเปลี่ยนสตริงให้ตรงกับตัวย่อจากตารางอื่น
Python เบื้องต้นสำหรับฐานข้อมูล

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับฐานข้อมูล

Preparing Video For Download...