import MySQLdb from ConnectionPool import ConnectionPool MYSQL_HOST = 'host' MYSQL_DB = 'database' MYSQL_USER = 'user' MYSQL_PASSWD = 'password' class Connection: def __init__(self): self.conn = MySQLdb.connect( host=MYSQL_HOST, db=MYSQL_DB, user=MYSQL_USER, passwd=MYSQL_PASSWD ) def getConnection(self): return self.conn def getCursor(self): return self.conn.cursor() if __name__ == '__main__': cpool = ConnectionPool(Connection, 5) # connection pool ÃʱâÈ­ mysql = cpool.get() # connection ¾ò¾î¿À±â print mysql mysql_conn = mysql.getConnection() mysql_conn.query('select * from userstatus') res = (mysql_conn.store_result()).fetch_row() print res cpool.put(mysql) # connection ¹ÝȯÇϱâ from Queue import Queue, Empty, Full class ConnectionPool(Queue): def __init__(self, constructor, poolsize=5): Queue.__init__(self, poolsize) self.constructor = constructor def get(self, block=1): try: return self.empty() and self.constructor() or Queue.get(self, block) except Empty: return self.constructor() def put(self, obj, block=1): try: return self.full() and None or Queue.put(self, obj, block) except Full: pass class Constructor: def __init__(self, function, *args, **kwargs): self.f = function self.args = args self.kwargs = kwargs def __call__(self): return apply(self.f, self.args, self.kwargs)