I recently discovered the Python with keyword and started seeing its potential usefulness for more prettily handling some scenarios where I
The Python DBAPI was written well before context managers were added to the Python language.
As such, different database libraries made their own decisions on how to implement context manager support (if they implemented it at all).
Usually using the database as a context manager ties you to a transaction. The transaction is started on __enter__, and committed or aborted on __exit__, depending on wether or not there was an exception. As such, you are supposed to use the MySQL connection as a context manager after connecting seperately:
connection = util.get_db_connection()
with connection as cursor:
cursor.execute(...)
# connection commit is issued if no exceptions were raised.
The sqlite3 context manager implementation is subtly different; it also manages transactions, but does not return a cursor from the __enter__ method:
con = sqlite3.connect(":memory:")
with con:
cursor = con.cursor()
# or use the connection directly
con.execute(...)
Technically, it just returns self on __enter__.