Python实现mysql连接池

编程入门 行业动态 更新时间:2024-10-26 22:18:01

Python实现mysql<a href=https://www.elefans.com/category/jswz/34/1766187.html style=连接池"/>

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连接池

本文发布于:2024-02-26 00:06:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1700706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接池   Python   mysql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!