Connessione al tuo database

Introduzione ai database in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Incontra SQLAlchemy

  • Due componenti principali
    • Core (incentrato sul modello relazionale)
    • ORM (incentrato sul modello dati utente)
Introduzione ai database in Python

Esistono molti tipi di database

  • SQLite
  • PostgreSQL
  • MySQL
  • Microsoft SQL Server
  • Oracle SQL
  • E molti altri
Introduzione ai database in Python

Connessione a un database

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
connection = engine.connect()
  • Engine: interfaccia comune al database fornita da SQLAlchemy
  • Stringa di connessione: tutti i dettagli per trovare il database (e fare login, se serve)
Introduzione ai database in Python

Una nota sulle stringhe di connessione

driverdialect.png

        Driver + Dialect

Introduzione ai database in Python

Una nota sulle stringhe di connessione

filename.png

                                                                                               Nome file

Introduzione ai database in Python

Cosa c’è nel tuo database?

Prima di interrogarlo, vuoi sapere cosa c’è nel database: ad esempio quali tabelle ci sono:

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
print(engine.table_names())
['census', 'state_fact']
Introduzione ai database in Python

Reflection

La reflection legge il database e crea oggetti Table di SQLAlchemy

from sqlalchemy import MetaData, Table

metadata = MetaData()
census = Table('census', metadata, autoload=True, autoload_with=engine)
print(repr(census))
Table('census', MetaData(bind=None), Column('state', VARCHAR(
length=30), table=<census>), Column('sex', VARCHAR(length=1),
table=<census>), Column('age', INTEGER(), table=<census>),
Column('pop2000', INTEGER(), table=<census>), Column('pop2008',
INTEGER(), table=<census>), schema=None)
Introduzione ai database in Python

Passiamo alla pratica!

Introduzione ai database in Python

Preparing Video For Download...