Úvod do SQL dotazů

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

SQL příkazy

  • Výběr, vkládání, aktualizace a mazání dat
  • Vytváření a úprava dat
Introduction to Databases in Python

Základní SQL dotazování

SELECT column_name FROM table_name

  • SELECT pop2008 FROM People
  • SELECT * FROM People
Introduction to Databases in Python

Základní SQL dotazování

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()
Introduction to Databases in Python

ResultProxy vs ResultSet

result_proxy = connection.execute(stmt)

results = result_proxy.fetchall()
  • result_proxy je ResultProxy
  • results je ResultSet
Introduction to Databases in Python

Práce s ResultSets

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'
Introduction to Databases in Python

SQLAlchemy pro tvorbu dotazů

  • Umožňuje pythonicky sestavovat SQL příkazy
  • Skrývá rozdíly mezi typy databázových backendů
Introduction to Databases in Python

Dotazování přes 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()
Introduction to Databases in Python

Příkaz select v SQLAlchemy

  • Vyžaduje seznam jedné nebo více tabulek či sloupců
  • Použití tabulky vybere všechny její sloupce
stmt = select([census])

print(stmt)
'SELECT * from CENSUS'
Introduction to Databases in Python

Lass uns üben!

Introduction to Databases in Python

Preparing Video For Download...