using third-party packages
https://pypi.python.org/pypi/DBUtils
TAR-ZXVF *.tar.gz * Python3 setup.py build && python3 setup.py Install
IMPORT TIMEIMPORT PYMYSQLIMPORT THREADINGFROM DBUTILS.POOLEDDB IMPORT POOLEDDB,  SHAREDDBCONNECTIONPOOL = POOLEDDB ( creator=pymysql, # The maximum number of connections allowed for modules maxconnections=6, # connection pools using linked databases, 0 and none means no limit on the number of connections mincached=2, # when initialized, the link pool creates at least idle links, 0 means no maxcached=5 is created, # link pool up to idle links, 0 and none limit the number of links that are most shared in the maxshared=3, # link pool, 0 and none means sharing all. ps: useless, because the pymysql and MYSQLDB modules such as threadsafety are 1, all values regardless of the number set to how much, _maxcached forever is 0, so forever is all links are shared. blocking=True, # If there are no available connections in the connection pool, wait is blocked. True, wait; False, do not wait and then error maxusage=None, # the number of times a link is reused, None means no limit setsession=[], # a list of commands to execute before starting the session. such as: ["set datestyle to , ....", "set time zone ..."] &nbSp;ping=0, # ping mysql Server, check if the service is available. # such as: 0 = none = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always host= ' 127.0.0.1 ', port=3306, user= ' root ', password= ' 123 ', database= ' pooldb ', charset= ' UTF8 ') def func (): # detects if the number of currently running connections is less than the maximum number of links, if not less than: Waits or reports Raise toomanyconnections exceptions # Otherwise # gets the link steadydbconnection in the link created when the initialization is first initialized. # then encapsulates the Steadydbconnection object into Pooleddedicateddbconnection and returns. # if the link you initially created is not linked, create a Steadydbconnection object and encapsulate it in pooleddedicateddbconnection and return. # once the link is closed, the connection is returned to the connection pool for subsequent threads to continue to use. conn = pool.connection () # print (th, ') Link was taken away ', conn1._con) # print (th, ' pond now has ', pool._idle_cache, ' \ r \ n ') cursor = conn.cursor () cursor.execute (' Select * from tb1 ') result = cursor.fetchall () #并没有关闭, just put the connection back in the connection Pool conn.close () func ()
Developing a custom MySQL connection pool