2008年9月25日星期四

[pitfall]python初始化数据库Connection时会关闭autocommit

[pitfall]python初始化数据库Connection时会关闭autocommit

之前用Django的model来存取数据库的数据,没有异常。现在要拆分数据库,因为Django不支持multiple database,所以使用了数据库直连的方法来解决,以前用到model的地方都要改为sql语句来实现。

上线后,跟踪系统日志,没有发现代码抛出任何异常。但是第二天发现报表有些数据不太正常。数据库的不少记录没有成功update。debug后发现是改成sql语句后导致部分涉及innodb表的写操作全部没有提交。

怀疑是数据库设置有问题,slelct @@autocommit;没有问题,是1。

一步一步调试,发现在MySQLdb初始化connection的时候,有这样的代码:

if self._transactional:
# PEP-249 requires autocommit to be initially off
self.autocommit(False)

原来是MySQLdb在搞鬼。不对啊,它为什么这么做呢?看它的注释:

# PEP-249 requires autocommit to be initially off

原来Python Database API Specification v2.0里面做了这样的规范:

.commit()

Commit any pending transaction to the database. Note that if the database supports an auto-commit feature, this must be initially off. An interface method may be provided to turn it back on.

Database modules that do not support transactions should implement this method with void functionality.

在在MySQLdb的FAQ里面也有说明。

教训:要多看文档,不能臆断其有无啊。

没有评论: