Skip to main content
 首页 » 编程设计

python之with-as 技术是否适用于 cx_Oracle

2025年05月04日11lyhabc

在最新版本的 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 技术。

请您参考如下方法: