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

后端 未结 2 1729
逝去的感伤
逝去的感伤 2021-01-02 04:01

Background

I recently discovered the Python with keyword and started seeing its potential usefulness for more prettily handling some scenarios where I

相关标签:
2条回答
  • 2021-01-02 04:46

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

    0 讨论(0)
  • 2021-01-02 04:54

    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.

    0 讨论(0)
提交回复
热议问题