【发布时间】:2015-10-01 05:09:39
【问题描述】:
MySQLdb Connections 有一个基本的上下文管理器,它在 enter 时创建一个游标,在 exit 时回滚或提交,并且不会隐式抑制异常。来自Connection source:
def __enter__(self):
if self.get_autocommit():
self.query("BEGIN")
return self.cursor()
def __exit__(self, exc, value, tb):
if exc:
self.rollback()
else:
self.commit()
那么,有谁知道为什么退出时光标没有关闭?
起初,我认为这是因为关闭游标没有做任何事情,并且游标只有一个关闭方法以尊重Python DB API(参见this answer 的cmets)。然而,事实是关闭游标会烧掉剩余的结果集(如果有的话),并禁用游标。来自cursor source:
def close(self):
"""Close the cursor. No further queries will be possible."""
if not self.connection: return
while self.nextset(): pass
self.connection = None
在退出时关闭光标会很容易,所以我不得不假设它不是故意的。另一方面,我们可以看到当一个游标被删除时,它无论如何都会关闭,所以我猜垃圾收集器最终会解决它。我对 Python 中的垃圾回收了解不多。
def __del__(self):
self.close()
self.errorhandler = None
self._result = None
另一种猜测是,可能存在您想在with 块之后重用光标的情况。但我想不出你需要这样做的任何理由。难道你不能总是在其上下文中使用完游标,而只为下一个事务使用单独的上下文吗?
说得很清楚,这个例子显然没有意义:
with conn as cursor:
cursor.execute(select_stmt)
rows = cursor.fetchall()
应该是:
with conn as cursor:
cursor.execute(select_stmt)
rows = cursor.fetchall()
这个例子也没有意义:
# first transaction
with conn as cursor:
cursor.execute(update_stmt_1)
# second transaction, reusing cursor
try:
cursor.execute(update_stmt_2)
except:
conn.rollback()
else:
conn.commit()
应该是:
# first transaction
with conn as cursor:
cursor.execute(update_stmt_1)
# second transaction, new cursor
with conn as cursor:
cursor.execute(update_stmt_2)
再说一遍,退出时关闭光标有什么害处,不关闭有什么好处?
【问题讨论】:
-
一个很好的解释>>> stackoverflow.com/questions/5669878/…
-
@syed 这是我的一个老问题,我也在这个问题中链接到它!
-
糟糕!没注意到。我想这个解释仍然成立。对此没有具体的答案,除此之外,您需要自行确定。
-
值得指出的是,
MySQLdb源对底层_mysql模块(与MySQLdb作为.pyd二进制文件一起分发)或the API it implements 提供的信息相对较少。我倾向于假设包作者遇到了以这种方式做事的理由,埋在其中一个依赖项中,或者它以 YAGNI 开始并以“没有损坏”而结束。
标签: python mysql mysql-python contextmanager