无论如何,在退出时关闭sqlite3数据库

时间:2013-11-16 02:59:03

标签: python error-handling sqlite resource-cleanup

我目前正在编写一个使用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)

程序退出而没有关闭连接后,我在尝试修改数据库时出错。

有没有办法安全地关闭连接,即使是在不干净的出口处?

1 个答案:

答案 0 :(得分:1)

说实话,我不太了解这个问题,但为什么不将poop.do_stuff()包裹在try/except块中呢?

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

完成所有代码后,或者在语句中发生异常后,__exit__将被执行,您可以安全地关闭它。

希望这有帮助!