我目前正在编写一个使用sqlite3的脚本。我最近遇到了另一个程序的问题,因为我的代码早期退出了一个错误。

存在类似的问题,通常使用:

conn = sqlite3.connect(...)
try:
    #Do stuff
finally:
    conn.close()
.

但这在我的情况下不会有效。简而言之,这是我的代码:

导入sqlite3

class Thingamadoodle:
    def __init__(self, ...):
        self.conn = sqlite3.connect(...)
        ...

    #Methods and stuff

    def __del__(self):
        self.conn.close()

poop = Thingamadoodle(...)
poop.do_stuff(...)
poop.throw_irritating_exception_that_you_cant_track_down(irritatingness=11)
.

程序在未关闭连接的情况下退出后,当我尝试修改数据库时,我会得到错误。

是否有一种方法可以安全地关闭连接,即使在不洁净的出口上?

有帮助吗?

解决方案

说实话,我不太了解这个问题,但为什么不仅仅是在世代odicetagcode块中包装的poop.do_stuff()

try:
    poop.do_stuff()
except:
    poop.__del__()
finally:
    poop.__del__()
.

或有点清洁,使用上下文管理器:

class Thingamadoodle:
    def __init__(self, ...):
        ...

    #Methods and stuff
    def __enter__(self):
        self.conn = sqlite3.connect(...)
        return self
    def __exit__(self, errorType, errorValue, errorTrace):
        self.conn.close()
.

并刚执行它为:

with Thingmadoodle(args) as poop:
    #do things
.

在完成所有代码之后,或在语句中发生异常后,将执行生成的,并且可以安全地关闭它。

希望这有帮助!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top