给tornado的database.py增加dbutils支持

忘记什么时候在邮件订阅中看到smallfish的一个给tornado的database.py增加dbutils支持的文章了,去smaillfish的blog看了一下居然是09年写的一篇文章。小鱼修改的代码为:

def reconnect(self):

"""Closes the existing database connection and re-opens it."""

self.close()

try:

from DBUtils import PooledDB

pool_con = PooledDB.PooledDB(creator=MySQLdb, **self._db_args)

self._db = pool_con.connection()

except:

self._db = MySQLdb.connect(**self._db_args)

self._db.autocommit(True)

小鱼干掉了原有的设置autocommit(True)这一行代码,我估计主要是因为DBUtils没有autocommit()这个方法。干掉此行代码后会有一个小问题,就是如果mysql配置的autocommit=0的话,每次对数据库的修改是不会实时反馈给mysql数据库的。而原版的self._db.autocommit(True)这一行就是为了在保证在执行完一条SQL后,修改内容马上反馈给mysql。

Google一圈后我找到两个解决方案:

  • 一个是利用DBUtils的的setsession命令:
    def reconnect(self):

    """Closes the existing database connection and re-opens it."""

    self.close()

    try:

    from DBUtils import PooledDB

    pool_con = PooledDB.PooledDB(creator=MySQLdb, setsession=['SET AUTOCOMMIT = 1'], **self._db_args)

    self._db = pool_con.connection()

    except:

    self._db = MySQLdb.connect(**self._db_args)

    self._db.autocommit(True)

  • 另一个就是类似tornado的做法给每个cursors的connection设置autocommit属性为True
    def reconnect(self):

    """Closes the existing database connection and re-opens it."""

    self.close()

    try:

    from DBUtils import PooledDB

    pool_con = PooledDB.PooledDB(creator=MySQLdb, **self._db_args)

    self._db = pool_con.connection()

    self._db.cursor().connection.autocommit(True)

    except:

    self._db = MySQLdb.connect(**self._db_args)

    self._db.autocommit(True)

已有8条评论 »

  1. 风起大神

    self._db.cursor().connection.autocommit(True)这个要改成self._db.cursor().autocommit(True)这样才会生效吧,我这里测试这样的.可以改一下

  2. As I web site possessor I believe the content material here is rattling great , appreciate it for your hard work. You should keep it up forever! Good Luck.

  3. As I web site possessor I believe the content material here is rattling great , appreciate it for your hard work. You should keep it up forever! Good Luck.

  4. cialis kaufen wien That skincare combo for a I Image skin to making off.

  5. As soon as I found this internet site I went on reddit to share some of the love with them.

  6. Liquid purchase viagra online Drink For Women in Friendswood .

  7. The best natural solution NATURAL viagra sale PLUS - THE KING OF SEX For professional and privet users.

  8. viagra sale for Sale USA Canada UK - Cialis Daily Use vs Viagra Reviews.

添加新评论 »