连接池"/>
Python实现mysql连接池
需要的安装包 python2.7:pip install DBUtils==2.0.3pip install pymysql==0.10.1
from dbutils.pooled_db import PooledDB
import pymysqlclass MysqlConnPool(object):pool = Nonemysql_host = "127.0.0.1"mysql_port = 3306mysql_user = "root"mysql_password = "password"mysql_database = "test"def __init__(self):self.db_host = self.mysql_hostself.db_port = self.mysql_portself.user = self.mysql_userself.password = self.mysql_passwordself.db = self.mysql_databaseself.conn = Noneself.cursor = Noneself._conn = self.connect_db()self._cursor = self._conn.cursor()# withdef __enter__(self):return self# withdef __exit__(self, exc_type, exc_val, exc_tb):self.release_connection()def connect_db(self):if self.pool is None:self.pool = PooledDB(creator=pymysql,maxconnections=10,maxcached=10,maxshared=10,blocking=True,setsession=[],host=self.db_host,port=self.db_port,user=self.user,password=self.password,database=self.db,charset='utf8',)return self.pool.connection()def release_connection(self):self._cursor.close()self._conn.close()# 获取全部数据def getalldata(self, sql):count = self._cursor.execute(sql)if count > 0:column = self._cursor.descriptionresult = self._cursor.fetchall()result_list = []for item in result:result_list.append({column[i][0]: item[i] for i in range(len(column))})return result_listelse:return []
更多推荐
Python实现mysql连接池
发布评论