For various reasons, including secrets handling, singleton connections
and so forth, I have a DBManager class that provides a DictCursor to
clients.
During instance initialization, the following are called in sequence:
def get_handle(self, name: str = None, logger: LoginLogger = None):
try:
self.conn = pymysql.connect(host=self.dsn,
user=self.db_user,
password=self.db_pass,
database=name.split('.')[1],
cursorclass=pymysql.cursors.DictCursor,
charset='utf8',
autocommit=True)
except Exception as e:
logger.log_msg('error', "exception trying to connect to %s
db: %r" % (name, e))
return False
return True
def _get_cursor(self):
#
https://pymysql.readthedocs.io/en/latest/user/examples.html
with self.conn:
with self.conn.cursor() as cursor:
self.cursor = cursor
and then clients can call:
def get_cursor(self):
return self.cursor
When I create a conn and get a cursor outside of a class in a python
shell using the same code and credentials, all is well. But when I do this:
dbc = dbm.get_cursor()
assert isinstance(dbc, DictCursor), "got back something that isn't a
DictCursor: %s" % type(dbc)
print("%r" % dbc)
rows = dbc.execute("SELECT 123")
I get (and note that the assert did not fail):
<pymysql.cursors.DictCursor object at 0x7f29d422d2e8>
Traceback (most recent call last):
File "./DBManagerTest.py", line 54, in <module>
rows = dbc.execute("SELECT 123")
File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 165,
in execute
while self.nextset():
File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 107,
in nextset
return self._nextset(False)
File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 91, in
_nextset
conn = self._get_db()
File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 73, in
_get_db
raise err.ProgrammingError("Cursor closed")
pymysql.err.ProgrammingError: Cursor closed
So I would appreciate suggestions on how to fix this so that cursor
stays open for even one query.
Best,
coyot