Gegevens in een tabel bijwerken

Introductie tot databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Gegevens in een tabel bijwerken

  • Met het update()-statement
  • Lijkt op insert() maar bevat een where-clausule om te bepalen welk record wordt bijgewerkt
  • Voeg alle waarden toe met de values()-clausule als kolom=waarde-paren
Introductie tot databases in Python

Eén rij bijwerken

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
Introductie tot databases in Python

Meerdere rijen bijwerken

  • Bouw een where-clausule die alle records selecteert die je wilt bijwerken
Introductie tot databases in Python

Meerdere rijen invoegen

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
Introductie tot databases in Python

Gecorreleerde 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
Introductie tot databases in Python

Gecorreleerde updates

  • Gebruikt een select()-statement om de waarde te vinden voor de kolom die we bijwerken
  • Vaak gebruikt om records op een maximum te zetten of een string aan te passen aan een afkorting uit een andere tabel
Introductie tot databases in Python

Laten we oefenen!

Introductie tot databases in Python

Preparing Video For Download...