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

六月ゝ 毕业季﹏ 提交于 2019-12-03 13:04:31

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

Vigneshwar Ponnusamy

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!