Python防止重复资源的链接mysql方法

配置连接池

配置连接池

POOL = PooledDB(

creator=pymysql,

maxconnections=5, # 连接池最大连接数

mincached=1, # 初始化时连接池至少创建的空闲连接数

maxcached=2, # 连接池最大空闲连接数

host="localhost",

port=3306,

user="root",

password="123456",

database="test_db",

charset="utf8mb4",

cursorclass=pymysql.cursors.DictCursor)

安装

PooledDB 是 DBUtils 库中实现数据库连接池的核心类,作用是复用数据库连接(避免频繁创建 / 关闭连接的性能损耗),尤其适合高并发 / 高频数据库操作的场景。下面从核心原理、完整使用示例、参数详解、最佳实践四部分讲解如何正确使用 PooledDB。

一、核心原理

连接池的本质是「预先创建一批数据库连接,存放在池中,当需要操作数据库时从池里取连接,用完后放回池里(不真正关闭)」,核心优势:

减少连接创建 / 销毁的开销(MySQL 创建连接的耗时远高于 SQL 执行);

控制最大连接数,避免数据库因连接过多崩溃;

自动管理连接的空闲 / 复用状态。

安装 PyMySQL

#pip install pymysql

#pip install DBUtils

报错

Traceback (most recent call last):

File "E:\demo\app4.py", line 3, in

from DBUtils.PooledDB import PooledDB # 需安装:pip install DBUtils

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

ModuleNotFoundError: No module named 'DBUtils'

既然终端显示 Requirement already satisfied: DBUtils in f:\tools\python\lib\site-packages (3.1.2)(DBUtils 已安装),但代码仍报 ModuleNotFoundError: No module named 'DBUtils',核心原因是运行代码的 Python 环境,和安装 DBUtils 的环境不一致(比如用了虚拟环境、IDE 解释器配置错误、多个 Python 版本冲突)。

下面按「优先级从高到低」给出解决方案,确保彻底匹配环境:

bash 复制代码
# 替换为你打印的Python路径(示例)
F:\tools\python\python.exe -m pip list | findstr DBUtils
# 卸载
F:\tools\python\python.exe -m pip uninstall -y DBUtils
# 方案1:阿里云源(稳定性高)
F:\tools\python\python.exe -m pip install DBUtils==3.1.2 -i https://mirrors.aliyun.com/pypi/simple/
# 方案2:豆瓣源
F:\tools\python\python.exe -m pip install DBUtils==3.1.2 -i https://pypi.doubanio.com/simple/
# 方案3:中科大源
F:\tools\python\python.exe -m pip install DBUtils==3.1.2 -i https://pypi.mirrors.ustc.edu.cn/simple/
# 方案4:官方源(无镜像限制,可能慢但稳定)
F:\tools\python\python.exe -m pip install DBUtils==3.1.2 --trusted-host pypi.org --trusted-host files.pythonhosted.org
相关推荐
AI攻城狮19 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽19 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程2 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪2 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook2 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python