2012-06-22 35 views
1

在Python的最新版本中,可以使用類似with open('abc.txt') as f:的東西來保證即使在以下(縮進)代碼塊中發生異常,文件也會關閉。我想知道這種技術是否也適用於cx_Oracle連接對象。例如,我可以做這樣的事情,以保證如果在隨後的代碼塊中發生錯誤的數據庫連接被關閉:with-as技術與cx_Oracle一起使用嗎?

with cx_Oracle.connect('uname/[email protected]') as conn: 
    c = conn.Cursor() 
    c.execute("Select * from table1") 
    #...etc 

目前我可以通過使用盡量的做到這一點......除了...最後,但我更喜歡with ... as技術。

回答

3

即使連接對象沒有做它本身(這顯然它),只要它提供了一個.close()方法,它會很容易使自己的包裝,使用contextlib.closing

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

其他變化幾乎同樣容易。

[在「是!」之前寫了上面的內容)答案已發佈,並決定發佈它。]