Is __enter__ and __exit__ behaviour for connection objects specified in the Python database API? Is __enter__ and __exit__ behaviour for connection objects specified in the Python database API? database database

Is __enter__ and __exit__ behaviour for connection objects specified in the Python database API?


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__.


See the __enter__ function in this link.https://github.com/PyMySQL/mysqlclient-python/blob/master/MySQLdb/connections.py

__enter__ function of connection object returns self.cursor().

That is why you are getting cursor object instead of Connection object.