Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy Core Connection Context Manager

Can I use a context manager for SQLAlchemy Core connections? In other words, is

conn = engine.connect()
conn.execute('SELECT * FROM FOO')
conn.close()

the same as

with engine.connect() as conn:
    conn.execute('SELECT * FROM FOO')

I don't need any checks for commits, rollbacks, etc at context manager exit.

like image 441
Matt Stern Avatar asked Jul 05 '13 22:07

Matt Stern


People also ask

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

Does SQLAlchemy close connection automatically?

connect() method returns a Connection object, and by using it in a Python context manager (e.g. the with: statement) the Connection. close() method is automatically invoked at the end of the block.

Does SQLAlchemy use connection pool?

SQLAlchemy includes several connection pool implementations which integrate with the Engine . They can also be used directly for applications that want to add pooling to an otherwise plain DBAPI approach.

Is SQLAlchemy engine thread safe?

Every pool implementation in SQLAlchemy is thread safe, including the default QueuePool . This means that 2 threads requesting a connection simultaneously will checkout 2 different connections. By extension, an engine will also be thread-safe.


1 Answers

You can use a connection as context manager.

See the connections's __enter__ and __exit__ methods for how this is implemented. __enter__ just returns self and __exit__ calls close.

Or you could just try it:

from sqlalchemy import create_engine
engine = create_engine("sqlite:///:memory:")
with engine.connect() as conn:
    print(conn.closed)
print(conn.closed)

output:

False
True
like image 179
mata Avatar answered Oct 28 '22 18:10

mata