Skip to content

Instantly share code, notes, and snippets.

@nomeyer
Last active February 10, 2016 20:52
Show Gist options
  • Save nomeyer/2644358c23cc89d1b530 to your computer and use it in GitHub Desktop.
Save nomeyer/2644358c23cc89d1b530 to your computer and use it in GitHub Desktop.
SQL query using sqlalchemy core
from sqlalchemy import create_engine
from sqlalchemy.engine.url import URL
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.expression import text as Text
def db_connect(db):
return create_engine(URL(**db)) # db should be a dict with connection params
db = {'drivername': 'postgresql', 'host': 'localhost', 'port': '5432',
'username': 'username', 'password': 'pw', 'database': 'db_name'}
session = sessionmaker(bind=db_connect(db))()
query = Text('SQL QUERY')
for row in session.execute(query).fetchall():
# do stuff with the data where type(row) == sqlalchemy.engine.result.RowProxy
session.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment