Bug #89113 Connector/Python cursors cannot act as a context manager
| Submitted: | 4 Jan 2018 23:12 | Modified: | 26 Jun 2020 21:52 |
|---|---|---|---|
| Reporter: | Chris Foresman | Email Updates: | |
| Status: | Closed | Impact on me: | |
| Category: | Connector / Python | Severity: | S4 (Feature request) |
| Version: | 8.0.5b1, 8.0.12 | OS: | Any |
| Assigned to: | CPU Architecture: | Any |
[11 Oct 2018 10:31]
MySQL Verification Team
Hello Chris Foresman, Thank you for the feature request! regards, Umesh
[27 Mar 2020 22:35]
Nuno Mariz
Posted by developer: Fixed by WL#13847
[26 Jun 2020 21:52]
Philip Olson
Posted by developer: Fixed as of the upcoming MySQL Connector/Python 8.0.21 release, and here's the proposed changelog entry from the documentation team: Implemented context management support to help allocate resources as needed. Thank you for the bug report. Note: this was fixed via WL #13847 ( via and MySQL bug #71663 )
Portions of this website are copyright © 2001, 2002 The PHP Group
Page generated in 0.040 sec. using MySQL 8.4.7-u6-cloud
Timestamp references displayed by the system are UTC.
Content reproduced on this site is the property of the
respective copyright holders.
It is not reviewed in advance
by Oracle and does not necessarily represent the opinion of
Oracle or any other party.
Description: Most Python DB-API 2.0 compliant drivers can create cursors as a context manager, like so: ```python with conn.cursor() as cur: cur.execute(query) result = cur.fetchone() print(result) ``` The cursor is created and assigned the identifier `cur`, and when exiting the scope, the cursor is automatically closed. How to repeat: Assuming a function `database_connection` that successfully creates a connection using Connector/Python: ```python >>> conn = database_connection() >>> with conn.cursor() as cur: ... cur.execute("""SELECT * FROM lab_order;""") ... cur.fetchall() ... Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: __enter__ ``` Suggested fix: Add `__enter__` and `__exit__` methods to the `Cursor` class to allow using it as a context manager. You can see a bit how psycopg2 does it (it's written using Python's C API since it's a compiled module) but basically you just return the cursor object with the `__enter__` method, and call `self.close(); return None` in the `__exit__` method. https://github.com/psycopg/psycopg2/blob/d2e86db8fb1fbf2f162d4e83dd66c96d48ac9a7d/psycopg/...