Skip to content

Instantly share code, notes, and snippets.

@joshlk
Last active December 8, 2017 14:43
Show Gist options
  • Save joshlk/228d2f44ac608f9541ef4acf640986a4 to your computer and use it in GitHub Desktop.
Save joshlk/228d2f44ac608f9541ef4acf640986a4 to your computer and use it in GitHub Desktop.
SQLAlchemy quickstart, tutorial

SQLAlchemy has two parts:

* ORM: this maps table and relationships between tables to Python objects
* Core: alows you to write and execute SQL using Python exspressions

Core

Select statment:

import pandas as pd
from sqlalchemy import select, cast, column, create_engine, Table, MetaData, insert

engine = create_engine("...")
metadata = MetaData(bind=engine, reflect=True)

table_X = metadata.tables['table_X']

sql = select([   # Dont use table_X.select() ass you cant specify columns
      table_X.columns('x')
    ]
).limit(10)

pd.read_sql_query(sql, engine)

To inspect an SQL statment:

str(sql) or print(sql)

To compile against SQL variant and include paramters:

print(select_i.compile(eng, compile_kwargs={"literal_binds": True}))

Other cheet sheet: https://www.pythonsheets.com/notes/python-sqlalchemy.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment