テーブルのデータを更新する

Pythonで学ぶデータベース入門

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

テーブルのデータを更新する

  • update() 文で実行
  • insert() に似るが、更新対象レコードを絞る where 句を含む
  • 変更する値は values()column=value の組で指定
Pythonで学ぶデータベース入門

1 行を更新

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で学ぶデータベース入門

相関更新

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で学ぶデータベース入門

相関更新

  • 更新対象列の値を取得するために select() を使用
  • 最大値への更新や、別テーブルの略称に合わせて文字列を変更する用途でよく使用
Pythonで学ぶデータベース入門

Passons à la pratique !

Pythonで学ぶデータベース入門

Preparing Video For Download...