Připojení k databázi

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Seznamte se: SQLAlchemy

  • Dvě hlavní části
    • Core (zaměřeno na relační model)
    • ORM (zaměřeno na uživatelský datový model)
Introduction to Databases in Python

Existuje mnoho typů databází

  • SQLite
  • PostgreSQL
  • MySQL
  • Microsoft SQL Server
  • Oracle SQL
  • A mnoho dalších
Introduction to Databases in Python

Připojení k databázi

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
connection = engine.connect()
  • Engine: společné rozhraní SQLAlchemy pro přístup k databázi
  • Connection string: všechny údaje potřebné k nalezení databáze (a případnému přihlášení)
Introduction to Databases in Python

Poznámka ke connection stringům

driverdialect.png

        Ovladač + dialekt

Introduction to Databases in Python

Poznámka ke connection stringům

filename.png

                                                                                               Název souboru

Introduction to Databases in Python

Co je v databázi?

Před dotazováním databáze je vhodné zjistit její obsah – například seznam tabulek:

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
print(engine.table_names())
['census', 'state_fact']
Introduction to Databases in Python

Reflexe

Reflexe načte databázi a vytvoří objekty Table v 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)
Introduction to Databases in Python

Pojďme cvičit!

Introduction to Databases in Python

Preparing Video For Download...