更新表中的数据

Python 中的数据库入门

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

更新表中的数据

  • 使用 update() 语句完成
  • 类似 insert(),但包含 where 子句以确定要更新的记录
  • values() 指定要更新的所有值,形式为 列=值
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 中的数据库入门

关联更新

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...