繁体   English   中英

with-as 技术是否适用于 cx_Oracle?

[英]Does the with-as technique work with cx_Oracle?

在最新版本的 python 中,可以使用类似with open('abc.txt') as f:来保证即使在以下(缩进的)代码块中发生异常也关闭文件。 我想知道这种技术是否也适用于 cx_Oracle 连接对象。 例如,如果在随后的代码块中发生错误,我是否可以做这样的事情来保证数据库连接关闭:

with cx_Oracle.connect('uname/pwd@schema.db') as conn:
  c = conn.Cursor()
  c.execute("Select * from table1")
  #...etc

目前我可以通过使用 try...except...finally 来实现这一点,但我更喜欢 with...as 技术。

即使 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!

其他变化几乎同样简单。

[上面写着“是的!” 答案已发布并决定无论如何都要发布它。]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM