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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With