python 数据库连接池

python 数据库连接池可以使用DBUtils模块。

示例程序:

#!/usr/bin/env python
# encoding:utf8

import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import time

import MySQLdb
from DBUtils.PooledDB import PooledDB

import lsconst

SLEEP_FOR_NEXT_TRY = 3

class DBTools:
    def __init__(self, host, user, passwd, db):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.db = db
        self.conn = None

    def connect(self):
        if self.conn:
            return

        while True:
            try:
                self.conn = PooledDB(MySQLdb, maxusage=10, db=self.db, host=self.host, user=self.user, passwd=self.passwd, charset='utf8')
                break
            except Exception, e:
                print lsconst.BRO, 'DBTools.connect', e, lsconst.NOR
                print 'Sleep %d seconds for next try.' % SLEEP_FOR_NEXT_TRY
                time.sleep(SLEEP_FOR_NEXT_TRY)

    def disconnect(self):
        if not self.conn:
            return
        try:
            #PooledDB instance has no attribute 'commit'
            #self.conn.commit()
            self.conn.close()
            self.conn = None

        except Exception, e:
            print lsconst.BRO, e, lsconst.NOR

    def operateDB(self, type, *sqls):
        if not self.conn:
            self.connect()
        try:
            pool = self.conn.connection()
            cur = pool.cursor()
            result = []
            if type == 'select':
                if cur.execute(sqls[0]) > 0:
                    #print sqls[0]
                    result = cur.fetchall()
                    pool.close()
                    return result
            else:
                for sql in sqls:
                    #print sql
                    cur.execute(sql)
                    pool.close()
                    return True
        except Exception, e:
            print lsconst.RED, e, lsconst.NOR
            print
            print lsconst.RED, sqls, lsconst.NOR

        #self.disconnect()

 

参考:

http://blog.csdn.net/gashero/article/details/1577187

 

原文:http://www.cnblogs.com/congbo/archive/2012/08/27/2658518.html

posted @ 2012-08-28 09:38  congbo  阅读(2249)  评论(0编辑  收藏  举报