Python Cheat Sheet
Python Cheat Sheet
Introduction to
Databases
Introduction to Databases in Python
New
F 0 120355 122194 New York NY state
York
New
F 1 118219 119661 Washington DC DC capitol
York
New
F 2 119577 116413 Washington WA state
York
Introduction to Databases in Python
New
F 0 120355 122194
York
New
F 1 118219 119661
York
New
F 2 119577 116413
York
Introduction to Databases in Python
New
F 0 120355 122194 New York NY state
York
New
F 1 118219 119661 Washington DC DC capitol
York
New
F 2 119577 116413 Washington WA state
York
INTRODUCTION TO DATABASES IN PYTHON
Let’s practice!
INTRODUCTION TO DATABASES IN PYTHON
Connecting
to a
Database
Introduction to Databases in Python
Meet SQLAlchemy
● Two Main Pieces
● Core (Relational Model focused)
● ORM (User Data Model focused)
Introduction to Databases in Python
Connecting to a database
In [1]: from sqlalchemy import create_engine
In [3]: print(engine.table_names())
Out[3]: ['census', 'state_fact']
Introduction to Databases in Python
Reflection
● Reflection reads database and builds SQLAlchemy Table
objects
In [1]: from sqlalchemy import MetaData, Table
In [4]: print(repr(census))
Out[4]:
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
Let’s practice!
INTRODUCTION TO DATABASES IN PYTHON
Introduction
to
SQL Queries
Introduction to Databases in Python
SQL Statements
● Select, Insert, Update & Delete data
● Create & Alter data
Introduction to Databases in Python
ResultProxy vs ResultSet
In [5]: result_proxy = connection.execute(stmt)
● ResultProxy
● ResultSet
Introduction to Databases in Python
Handling ResultSets
In [1]: first_row = results[0]
In [2]: print(first_row)
Out[2]: ('Illinois', 'M', 0, 89600, 95012)
In [4]: print(first_row.keys())
Out[4]: ['state', 'sex', 'age', 'pop2000', 'pop2008']
In [6]: print(first_row.state)
Out[6]: 'Illinois'
Introduction to Databases in Python
SQLAlchemy querying
In [4]: from sqlalchemy import Table, MetaData
In [10]: print(stmt)
Out[10]: 'SELECT * from CENSUS'
INTRODUCTION TO DATABASES IN PYTHON
Let’s practice!
INTRODUCTION TO DATABASES IN PYTHON
Congratulations!
Introduction to Databases in Python
You already
● Know about the relational model
● Can make basic SQL queries
Introduction to Databases in Python
Coming up next…
● Beef up your SQL querying skills
● Learn how to extract all types of useful information
from your databases using SQLAlchemy
● Learn how to create and write to relational databases
● Deep dive into the US census dataset!
INTRODUCTION TO DATABASES IN PYTHON