[英]Does the with-as technique work with cx_Oracle?
In recent versions of python, one can use something like with open('abc.txt') as f:
to guarantee that the file is closed even if an exception occurs in the following (indented) code block.在最新版本的 python 中,可以使用类似
with open('abc.txt') as f:
来保证即使在以下(缩进的)代码块中发生异常也关闭文件。 I was wondering if this technique would also work for cx_Oracle connection objects.我想知道这种技术是否也适用于 cx_Oracle 连接对象。 For example, could I do something like this to guarantee the database connection gets closed if an error occurred in the subsequent code block:
例如,如果在随后的代码块中发生错误,我是否可以做这样的事情来保证数据库连接关闭:
with cx_Oracle.connect('uname/pwd@schema.db') as conn:
c = conn.Cursor()
c.execute("Select * from table1")
#...etc
Currently I can accomplish this through the use of try...except...finally, but I prefer the with...as technique.目前我可以通过使用 try...except...finally 来实现这一点,但我更喜欢 with...as 技术。
Even if the Connection object didn't do it itself (which apparently it does), as long as it provided a .close()
method it'd be easy to make your own wrapper, using contextlib.closing即使 Connection 对象本身没有这样做(显然它确实这样做了),只要它提供了
.close()
方法,使用contextlib.closure就可以轻松制作自己的包装器
>>> from contextlib import closing
>>>
>>> class FakeC(object):
... def close(self):
... print 'closing!'
... def execute(self, cmd):
... print cmd
...
>>> with closing(FakeC()) as c:
... c.execute("fred")
... raise Exception("something went wrong!")
...
fred
closing!
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
Exception: something went wrong!
And other variations are almost as easy.其他变化几乎同样简单。
[Wrote the above before the "Yes!" [上面写着“是的!” answer was posted and decided to publish it anyway.]
答案已发布并决定无论如何都要发布它。]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.