更新資料表中的資料

Python 資料庫入門

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

更新資料表中的資料

  • 使用 update() 陳述式
  • 類似 insert(),但加入 where 子句來決定要更新哪些紀錄
  • 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 子句以選出要更新的所有紀錄
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...