Gegevens filteren en targeten

Introductie tot databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Where-clausules

stmt = select([census])

stmt = stmt.where(census.columns.state == 'California')
results = connection.execute(stmt).fetchall()
for result in results: print(result.state, result.age)
California 0
California 1
California 2
California 3
California 4
California 5
...
Introductie tot databases in Python

Where-clausules

  • Beperk data die een query retourneert op basis van booleaanse voorwaarden
  • Vergelijk een kolom met een waarde of een andere kolom
  • Gebruik vaak vergelijkingen ==, <=, >= of !=
Introductie tot databases in Python

Expressies

  • Bieden complexere voorwaarden dan simpele operators
  • Bijv. in_(), like(), between()
  • Veel meer in de documentatie
  • Beschikbaar als methode op een Column
Introductie tot databases in Python

Expressies

stmt = select([census])

stmt = stmt.where(census.columns.state.startswith('New'))
for result in connection.execute(stmt): print(result.state, result.pop2000)
New Jersey 56983
New Jersey 56686
New Jersey 57011
...
Introductie tot databases in Python

Conjuncties

  • Hiermee kun je meerdere criteria in één where-clausule zetten
  • Bijv. and_(), or_(), not_()
Introductie tot databases in Python

Conjuncties

from sqlalchemy import or_

stmt = select([census])
stmt = stmt.where( or_(census.columns.state == 'California', census.columns.state == 'New York' ) )
for result in connection.execute(stmt): print(result.state, result.sex)
New York M
...
California F
Introductie tot databases in Python

Laten we oefenen!

Introductie tot databases in Python

Preparing Video For Download...