Introduzione alle query SQL

Introduzione ai database in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Istruzioni SQL

  • Seleziona, inserisce, aggiorna ed elimina dati
  • Crea e modifica dati
Introduzione ai database in Python

Query SQL di base

SELECT column_name FROM table_name

  • SELECT pop2008 FROM People
  • SELECT * FROM People
Introduzione ai database in Python

Query SQL di base

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()
Introduzione ai database in Python

ResultProxy vs ResultSet

result_proxy = connection.execute(stmt)

results = result_proxy.fetchall()
  • result_proxy è un ResultProxy
  • results è un ResultSet
Introduzione ai database in Python

Gestire i ResultSet

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'
Introduzione ai database in Python

Costruire query con SQLAlchemy

  • Offre un modo “pythonic” per creare istruzioni SQL
  • Nasconde le differenze tra i vari database backend
Introduzione ai database in Python

Query con 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()
Introduzione ai database in Python

Istruzione select in SQLAlchemy

  • Richiede una lista di una o più tabelle o colonne
  • Usare una tabella seleziona tutte le sue colonne
stmt = select([census])

print(stmt)
'SELECT * from CENSUS'
Introduzione ai database in Python

Passons à la pratique !

Introduzione ai database in Python

Preparing Video For Download...