Skip to content

Instantly share code, notes, and snippets.

@mikefromit
Created September 12, 2016 20:03
Show Gist options
  • Save mikefromit/4412b790a47bf33d36cf52c012abbf2c to your computer and use it in GitHub Desktop.
Save mikefromit/4412b790a47bf33d36cf52c012abbf2c to your computer and use it in GitHub Desktop.
A quick script using sqlalchemy for query development
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
def create_sa_connection(connection_string):
""" A nice helper function for creating the session and engine required
for sqlalchemy interactions with the database.
:param connection:
:return:
"""
engine = create_engine(connection, echo=False)
Session = sessionmaker(bind=engine)
session = Session()
return engine, session
# The connection string for connecting to the database
connection_string = 'postgresql+psycopg2://db_user:db_password@localhost:5432/db'
# Get the engine and the session we need to use engine for core and session for orm
engine, session = create_sa_connection(connection_string)
# Reflect the database to allow for declarative and using core
Base = automap_base()
Base.prepare(engine, reflect=True)
# Create a class for a specific table
User = Base.classes.users
# Write a query to get those users
users = session.query(User).all()
# Display all the user emails in the Users table
for user in users:
print(user.email)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment