Filtrera och rikta data

Introduktion till databaser i Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Where-satser

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
...
Introduktion till databaser i Python

Where-satser

  • Begränsar returnerade data baserat på booleska villkor
  • Jämför en kolumn mot ett värde eller en annan kolumn
  • Använder ofta jämförelserna ==, <=, >= eller !=
Introduktion till databaser i Python

Uttryck

  • Ger mer komplexa villkor än enkla operatorer
  • T.ex. in_(), like(), between()
  • Många fler finns i dokumentationen
  • Tillgängliga som metod på en Column
Introduktion till databaser i Python

Uttryck

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
...
Introduktion till databaser i Python

Konjunktioner

  • Möjliggör flera villkor i en where-sats
  • T.ex. and_(), or_(), not_()
Introduktion till databaser i Python

Konjunktioner

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
Introduktion till databaser i Python

Nu kör vi en övning!

Introduktion till databaser i Python

Preparing Video For Download...