I'm using SQLAlchemy's ORM to construct queries with a ContextManager to manage the session. It's been suggested that you can get Pandas' read_sql
working with a Query
object by read_sql(sql=q.statement, con=q.session.bind)
however this doesn't work within a with
block.
For example, the following setup results in an UnboundExecutionError
. I think the session
is somehow not bound.
@contextmanager
def db_session():
session = Session()
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()
class MyTable(Base):
__tablename__ = 'MyTables'
__table_args__ = {'schema': 'MyDatabase.dbo'}
A = Column(Integer)
B = Column(String(100, 'SQL_Latin1_General_CP1_CI_AS'))
with db_session() as s:
q = s.query(table.A, table.B).filter(table.A >= 10)
q = q.yield_per(1000).enable_eagerloads(False)
results = pd.read_sql(sql=q.statement, con=q.session.bind)
pd.DataFrame(results, columns=['A', 'B'])
sqlalchemy.exc.UnboundExecutionError: This session is not bound to a single Engine or Connection, and no context was provided to locate a binding.