[英]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.