MySQL connection method without connection pooling
Import MySQLdb
conn= mysqldb.connect (host= ' localhost ', user= ' root ', passwd= ' pwd ', db= ' MyDB ', port=3306) cur=conn.cursor () sql= " SELECT * FROM table1 "R=cur.execute (SQL) R=cur.fetchall () Cur.close () Conn.close ()
Connection method after using the connection pool
Import MySQLdb
From DBUTILS.POOLEDDB import pooleddb
Pool = pooleddb (mysqldb,5,host= ' localhost ', user= ' root ', passwd= ' pwd ', db= ' MyDB ', port=3306) #5为连接池里的最少连接数
conn = Pool.connection () #以后每次需要数据库连接就是用connection () function Get the connection just fine.
Cur=conn.cursor () sql= "SELECT * FROM table1" R=cur.execute (SQL) R=cur.fetchall () Cur.close () Conn.close ()
Parameters of the POOLEDDB:
1. mincached, minimum number of idle connections, if the number of idle connections is less than this, pool creates a new connection
2. maxcached, the maximum number of idle connections, if the number of idle connections is greater than this, pool closes the idle connection
3. MaxConnections, maximum number of connections,
4. Blocking, when the number of connections reaches the maximum number of connections, when the connection is requested, if this value is true, the program requesting the connection will wait until the current number of connections is less than the maximum number of connections, if this value is False, will be error,
5. Maxshared when the number of connections reaches this number, the newly requested connection will share the connection that has been allocated
In Uwsgi, each HTTP request is distributed to a process in which the number of connections configured in the connection pool is a process unit (that is, the maximum number of connections above, the number of connections in a process), and if the business The number of SQL connections required in an HTTP request is not many (most of them only need to create a connection) and the configured number of connections is not configured to be too large.
The performance improvement of the connection pool is shown in:
1. When the program creates a connection, it can be obtained from an idle connection, without having to reinitialize the connection to increase the speed of getting the connection.
2. When the connection is closed, put the connection back into the connection pool instead of the real shutdown, so you can reduce the frequent opening and closing of the connection
dbutils:https://pypi.python.org/pypi/dbutils/
Translated from: http://www.cnblogs.com/Xjng/p/3437694.html
Python database connection Pool instance--pooleddb