Introduction to SQL queries

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

SQL Statements

  • Select, insert, update, and delete data
  • Create and alter data
Introduction to Databases in Python

Basic SQL querying

SELECT column_name FROM table_name

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

Basic SQL querying

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 is a ResultProxy
  • results is a ResultSet
Introduction to Databases in Python

Handling 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 to build queries

  • Provides a Pythonic way to build SQL statements
  • Hides differences between backend database types
Introduction to Databases in Python

SQLAlchemy querying

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

SQLAlchemy select statement

  • Requires a list of one or more Tables or Columns
  • Using a table will select all the columns in it
stmt = select([census])

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

Let's practice!

Introduction to Databases in Python

Preparing Video For Download...