The following describes how to use the Python database connection pool in a multi-threaded environment. If you are interested in the steps related to the application of the Python database connection pool in its specific solution, you can click the following article to learn about it.
Example:
- #-*-coding:utf-8-*-
- import threading,time,datetime
- import MySQLdb
- from DBUtils import PooledDB
- pool = PooledDB.PooledDB(MySQLdb,100,50,100,490,False,
host='localhost',user='root',passwd='321',db='test',
charset='utf8')
By default, the system creates 100 database connections. Check and find that there are 100 Databases
- class MyThread(threading.Thread):
- def __init__(self,threadName):
- self.conn = pool.connection()
Extract from database connection pool directly
- threading.Thread.__init__(self,name=threadName)
- def run(self):
- cursor=self.conn.cursor()
- print "hello--->",self.getName()
- file_objct = open('8.txt','a+')
- file_objct.write(self.getName()+'\n')
- file_objct.close()
- #cursor.execute("call loaddate();")
- #self.conn.commit()
- time.sleep(10)
- def __del__(self):
- self.conn.close()
- self.conn = None
- for i in range(5):
- obj = MyThread(str(i))
- obj.start()
-
If I open 480 threads, the database will display 480 connections! Maxconnections: Maximum number of allowed connections (0 by default indicates no limit). If I adjust the Code as follows:
- #-*-coding:utf-8-*-
- import threading,time,datetime
- import MySQLdb
- from DBUtils import PooledDB
- pool = PooledDB.PooledDB(MySQLdb,100,50,100,400,False,
host='localhost',user='root',passwd='321',db='test',
charset='utf8')
- class MyThread(threading.Thread):
- def __init__(self,threadName):
- self.conn = pool.connection()
- threading.Thread.__init__(self,name=threadName)
- def run(self):
- cursor=self.conn.cursor()
- print "hello--->",self.getName()
- file_objct = open('8.txt','a+')
- file_objct.write(self.getName()+'\n')
- file_objct.close()
- #cursor.execute("call loaddate();")
- #self.conn.commit()
- time.sleep(10)
- def __del__(self):
- self.conn.close()
- self.conn = None
- for i in range(402):
- obj = MyThread(str(i))
- obj.start()
The maximum number of connection pools is 400.