session.execute() versus connection.execute()

605 views
Skip to first unread message

Felix Zumstein

unread,
Sep 15, 2013, 7:46:32 AM9/15/13
to sqlal...@googlegroups.com
All samples for the ORM part use a session to connect to the database, whereas all samples in the Core part use a connection. If I use both approaches in my app, does it make sense to execute the SQL Expression Language (Core) through session.execute() or is there a reason I should use connection.execute()?

For example, can I say:

from sqlalchemy.sql import select
from models import User
from main import session_scope

users = User.__table__

with session_scope() as session:
    result = session.execute(select([users]))


session_scope() is a context manager as described here.


Michael Bayer

unread,
Sep 15, 2013, 8:23:51 PM9/15/13
to sqlal...@googlegroups.com
what's going on with connections is that they represent some kind of ongoing state within a transaction (or not).   If you were to just say engine.execute(), or connection.execute() where you didn't begin() a transaction, then your statement executes on an arbitrary connection and autocommits.  If OTOH you use Session.execute(), you're using the Connection that specifically is associated with that Session, which normally is also ongoing within a transaction (you can get at this Connection by saying Session.connection() also).   What's important here is if you want your statement to occur along with the same transaction as all the other operations you're doing (usually you do).

signature.asc
Reply all
Reply to author
Forward
0 new messages