Introductie tot SQL-queries

Introductie tot databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

SQL-statements

  • Selecteren, invoegen, bijwerken en verwijderen van data
  • Data maken en wijzigen
Introductie tot databases in Python

Basis SQL-querying

SELECT column_name FROM table_name

  • SELECT pop2008 FROM People
  • SELECT * FROM People
Introductie tot databases in Python

Basis SQL-querying

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
connection = engine.connect()
stmt = 'SELECT * FROM people'
result_proxy = connection.execute(stmt)
results = result_proxy.fetchall()
Introductie tot databases in Python

ResultProxy vs ResultSet

result_proxy = connection.execute(stmt)

results = result_proxy.fetchall()
  • result_proxy is een ResultProxy
  • results is een ResultSet
Introductie tot databases in Python

ResultSets gebruiken

first_row = results[0]
print(first_row)
('Illinois', 'M', 0, 89600, 95012)
print(first_row.keys())
['state', 'sex', 'age', 'pop2000', 'pop2008']
print(first_row.state)
'Illinois'
Introductie tot databases in Python

SQLAlchemy voor queries bouwen

  • Biedt een Pythonic manier om SQL-statements te bouwen
  • Verbergt verschillen tussen databasetypes
Introductie tot databases in Python

Queryen met SQLAlchemy

from sqlalchemy import Table, MetaData
metadata = MetaData()

census = Table('census', metadata, autoload=True, autoload_with=engine)
stmt = select([census])
results = connection.execute(stmt).fetchall()
Introductie tot databases in Python

SQLAlchemy select-statement

  • Vereist een lijst met één of meer Tables of Columns
  • Een tabel selecteren kiest alle kolommen erin
stmt = select([census])

print(stmt)
'SELECT * from CENSUS'
Introductie tot databases in Python

Laten we oefenen!

Introductie tot databases in Python

Preparing Video For Download...