Creare database e tabelle

Introduzione ai database in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Creare database

  • Varia in base al tipo di database
  • Database come PostgreSQL e MySQL hanno tool da riga di comando per inizializzare il database
  • Con SQLite, l’istruzione create_engine() crea il database e il file se non esistono già
Introduzione ai database in Python

Creare una tabella

from sqlalchemy import (Table, Column, String, 
       Integer, Decimal, Boolean)

employees = Table('employees', metadata, Column('id', Integer()), Column('name', String(255)), Column('salary', Decimal()), Column('active', Boolean()))
metadata.create_all(engine)
engine.table_names()
[u'employees']
Introduzione ai database in Python

Creare tabelle

  • Usa ancora l’oggetto Table, come per la reflection
  • Sostituisce l’argomento autoload con oggetti Column
  • Crea le tabelle nel database con create_all() sull’istanza MetaData
  • Per aggiornare le tabelle usa altri strumenti, es. Alembic o SQL grezzo
Introduzione ai database in Python

Creare tabelle - opzioni aggiuntive per le colonne

  • unique impone valori unici nella colonna
  • nullable indica se una colonna può essere vuota
  • default imposta un valore predefinito se non fornito
Introduzione ai database in Python

Creare una tabella con opzioni aggiuntive

employees = Table('employees', metadata,
       Column('id', Integer()), 
       Column('name', String(255), unique=True, nullable=False), 
       Column('salary', Float(), default=100.00),          
       Column('active', Boolean(), default=True))

employees.constraints
{CheckConstraint(... 
Column('name', String(length=255), table=<employees>, nullable=False), 
Column('salary', Float(), table=<employees>, 
       default=ColumnDefault(100.0)), 
Column('active', Boolean(), table=<employees>, 
       default=ColumnDefault(True)), ...
UniqueConstraint(Column('name', String(length=255), 
                 table=<employees>, nullable=False))}
Introduzione ai database in Python

Passiamo alla pratica !

Introduzione ai database in Python

Preparing Video For Download...