Python使用连接池操作MySQL

测试环境说明:Python版本是 3.8.10 ,DBUtils版本是3.1.0 ,pymysql版本是1.0.3

  1. 首先安装指定版本的连接池库DBUtils 、还有pymysql
python 复制代码
pip install DBUtils==3.1.0
pip install pymysql==1.0.3
  1. 创建文件 sqlConfig.py
python 复制代码
# sqlConfig.py

import pymysql
from dbutils.pooled_db import PooledDB
# 有些版本使用下面语句引入,要注意一下
# from DBUtils.PooledDB import PooledDB

host = '127.0.0.1'
port = 3306
user = 'myname'
password = 'mypass'
database = 'contest'

class MySQLConnectionPool:
    def __init__(self,):
        self.pool = PooledDB(
            creator=pymysql,  # 使用链接数据库的模块
            mincached=10,  # 初始化时,链接池中至少创建的链接,0表示不创建
            maxconnections=200,  # 连接池允许的最大连接数,0和None表示不限制连接数
            blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
            host=host,
            port=port,
            user=user,
            password=password,
            database=database
        )

    def open(self):
        self.conn = self.pool.connection()
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)  # 表示读取的数据为字典类型
        return self.conn, self.cursor

    def close(self, cursor, conn):
        cursor.close()
        conn.close()

    def select_one(self, sql, *args):
        """查询单条数据"""
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchone()
        self.close(conn, cursor)
        return result

    def select_all(self, sql, args):
        """查询多条数据"""
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchall()
        self.close(conn, cursor)
        return result

    def insert_one(self, sql, args):
        """插入单条数据"""
        self.execute(sql, args, isNeed=True)

    def insert_all(self, sql, datas):
        """插入多条批量插入"""
        conn, cursor = self.open()
        try:
            cursor.executemany(sql, datas)
            conn.commit()
            return {'result': True, 'id': int(cursor.lastrowid)}
        except Exception as err:
            conn.rollback()
            return {'result': False, 'err': err}

    def update_one(self, sql, args):
        """更新数据"""
        self.execute(sql, args, isNeed=True)

    def delete_one(self, sql, *args):
        """删除数据"""
        self.execute(sql, args, isNeed=True)

    def execute(self, sql, args, isNeed=False):
        """
        执行
        :param isNeed 是否需要回滚
        """
        conn, cursor = self.open()
        if isNeed:
            try:
                cursor.execute(sql, args)
                conn.commit()
            except:
                conn.rollback()
        else:
            cursor.execute(sql, args)
            conn.commit()
        self.close(conn, cursor)
  1. 创建文件 sqlTest.py ,并引入sqlConfig.py使用
python 复制代码
# sqlTest.py

# 引入连接池类
from sqlConfig import MySQLConnectionPool

# 创建连接池对象
ConnPool = MySQLConnectionPool()

# 模糊查询
strSelectAll = "select * from names where name like %s"
results = ConnPool.select_all(strSelectAll, ('%唐%',))
print(results)

# 精确查询
# strSelectAll = "select * from names where name=%s"
# results = ConnPool.select_all(strSelectAll, ('唐三',))
# print(results)

# 单条查询
# strSelectOne = 'select * from `names` where `name`=%s'
# results = ConnPool.select_one(strSelectOne, ('唐三',))
# print(results)

# 单条插入
# strInsertOne = "insert into `names` (`name`, sex, age) values (%s,%s,%s)"
# ConnPool.insert_one(strInsertOne, ('唐三', '男', 22))

# 批量插入
# datas = [
#     ('戴沐白', '男', 26),
#     ('奥斯卡', '男', 26),
#     ('唐三', '男', 25),
#     ('小舞', '女', 100000),
#     ('马红俊', '男', 23),
#     ('宁荣荣', '女', 22),
#     ('朱竹清', '女', 21),
# ]
# sql_insert_all = "insert into `names` (`name`, sex, age) values (%s,%s,%s)"
# ConnPool.insert_all(sql_insert_all, datas)

# sql_update_one = "update `names` set age=%s where `name`=%s"
# ConnPool.update_one(sql_update_one, (28, '唐三'))

# sql_delete_one = 'delete from `names` where `name`=%s '
# ConnPool.delete_one(sql_delete_one, ('唐三',))

运行代码

相关推荐
iFeng的小屋几秒前
【2026最新当当网爬虫分享】用Python爬取千本日本相关图书,自动分析价格分布!
开发语言·爬虫·python
民乐团扒谱机3 分钟前
【微科普】3D 演奏蠕虫分析图:解码音乐表演情感的 “可视化语言”
python·可视化·音乐·3d图·3d蠕虫
芝士爱知识a9 分钟前
AlphaGBM 深度解析:下一代基于 AI 与蒙特卡洛的智能期权分析平台
数据结构·人工智能·python·股票·alphagbm·ai 驱动的智能期权分析·期权
qinyia37 分钟前
通过本地构建解决Cartographer编译中absl依赖缺失问题
linux·运维·服务器·mysql·ubuntu
霖霖总总43 分钟前
[小技巧65]深入 InnoDB 页的逻辑存储结构:16KB 页的逻辑全景解析
数据库·mysql
52Hz1181 小时前
力扣230.二叉搜索树中第k小的元素、199.二叉树的右视图、114.二叉树展开为链表
python·算法·leetcode
喵手1 小时前
Python爬虫实战:网页截图归档完全指南 - 构建生产级页面存证与历史回溯系统!
爬虫·python·爬虫实战·零基础python爬虫教学·网页截图归档·历史回溯·生产级方案
张3蜂1 小时前
Python 四大 Web 框架对比解析:FastAPI、Django、Flask 与 Tornado
前端·python·fastapi
2601_948374571 小时前
商用电子秤怎么选
大数据·python