程序运行久了会出现数据库连接超时失效的错误,因为我把数据库连接放到了模块级别了,那么所有的类都可以使用这个connection,我想当然的这么做,因为我不想自己去频繁处理连接。也想把关闭连接的动作放到类的__del__方法中去,但是总觉得这样麻烦,所以放到了模块级。今天去翻看了一下pyhton DBAPI PEP249,看到了这样的两段关于close方法的说明:
cursor:
.close()
Close the cursor now (rather than whenever __del__ is
called). The cursor will be unusable from this point
forward; an Error (or subclass) exception will be raised
if any operation is attempted with the cursor.
.close()
Close the connection now (rather than whenever __del__ is
called). The connection will be unusable from this point
forward; an Error (or subclass) exception will be raised
if any operation is attempted with the connection. The
same applies to all cursor objects trying to use the
connection. Note that closing a connection without
committing the changes first will cause an implicit
rollback to be performed.
显示的调用close方法可以马上关闭连接,但是DBAPI应该在__del__方法中显示关闭数据库连接的操作,因此其实使用符合DBAPI标准的数据库Driver就根本自己不用去管连接的问题了,你初始化一个connection之后,如果connection被GC收集,那么连接会自动释放的!

没有评论:
发表评论