Written without database connection pool:
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()
Use PooledDB
from DBUtils.PooledDB import PooledDB import pymysql import xlwt import os import threading import zipfile class CreateExcel(object): """ 查询数据库,并生成excel 文档 """ def __init__(self, mysql_info): self.mysql_info = mysql_info self.pool = PooledDB(pymysql, 5, host=self.mysql_info['host'], user=self.mysql_info['user'], password=self.mysql_info['password'], db=self.mysql_info['db'], port=self.mysql_info['port'], charset='utf-8')
Connection parameters are defined:
1. mincached, the minimum number of idle connections, idle connection number is less than this number, the pool will create a new connection
2. maxcached, the maximum number of idle connections, if this number is greater than the number of idle connections, the pool will close idle connections
3. MaxConnections, the maximum number of connections,
4. blocking, when the number of connections reaches the maximum number of connections, when the request for connection, if this value is True, the connection request program waits until the current number of connections less than the maximum number of connections, If this value is False, being given,
5. the maxshared when this number reaches the number of connections, a new connection request for share allocation already connected
5 here should be the default number of connections it
In uwsgi, each http request process will be distributed to a number of connection pool is configured as a process (ie, the maximum number of connections above, are the number of connections in a process) units, and if the business in a http request needs sql connections are not a lot of words (in fact, most only need to create a connection), the number of connections configuration do not need much.
Connection pooling to enhance performance in:
1, can be obtained when the program creates a connection from an idle connection, do not need to re-initialize the connection to improve acquisition speed connection
when 2. Turn off the connection, the connection back connection pool, rather than real close, it is possible to reduce the frequent opening and closing connections