Mat*_* C. 8 python cx-oracle with-statement
cx_Oracle包含__enter__和__exit__Connection对象上,而不是在游标对象.因此,我到处使用它来包装游标:
class CursorWrapper(object):
def __init__(self, connection):
self.connection = connection
self.cursor = None
def __enter__(self):
self.cursor = self.connection.cursor()
return self.cursor
def __exit__(self, exc_type, exc_value, traceback):
self.cursor.close()
Run Code Online (Sandbox Code Playgroud)
然后,当我想要一个光标
with CursorWrapper(cnx) as cursor:
cursor.execute("whatever sql statement")
Run Code Online (Sandbox Code Playgroud)
它非常适合我的需求.
但是,我当时想知道什么可以阻止__enter__和__exit__方法直接添加到cx_Oracle中?
或者是否有更好的方法将游标与上下文管理一起使用,这可以解释为什么它没有在模块中定义?
编辑:对不起,我刚刚找到答案.我可以使用contextlib.closing.
import contextlib
with contextlib.closing(cnx.cursor()) as cursor:
Run Code Online (Sandbox Code Playgroud)
解决方案来自@MathieuC。的提问帖。
我可以只使用 contextlib. opening 。
Run Code Online (Sandbox Code Playgroud)import contextlib with contextlib.closing(cnx.cursor()) as cursor:
| 归档时间: |
|
| 查看次数: |
899 次 |
| 最近记录: |