PyMySQL连接超时的解决方法
通过以上方法,应该能够解决大多数PyMySQL连接超时的问题。connect_timeout=30,# 默认是10秒,这里增加到30秒。wait_timeout = 28800# 连接空闲超时时间(秒)read_timeout=30,# 读取操作超时。write_timeout=30# 写入操作超时。检查防火墙设置是否阻止了MySQL端口(默认3306)检查MySQL服务器CPU、内存使用情况。检
PyMySQL 连接超时解决方法
当使用 PyMySQL 连接 MySQL 数据库时遇到连接超时问题,可以通过以下几种方法解决:
1. 增加连接超时时间
import pymysql
connection = pymysql.connect(
host='your_host',
user='your_username',
password='your_password',
database='your_database',
connect_timeout=30, # 默认是10秒,这里增加到30秒
read_timeout=30, # 读取操作超时
write_timeout=30 # 写入操作超时
)
2. 检查网络连接
确保你的应用服务器和MySQL服务器之间的网络连接正常:
使用 ping 命令测试网络连通性
检查防火墙设置是否阻止了MySQL端口(默认3306)
3. 调整MySQL服务器配置
在MySQL服务器端修改以下参数(在my.cnf或my.ini中):
[mysqld]
wait_timeout = 28800 # 连接空闲超时时间(秒)
interactive_timeout = 28800
max_connections = 200 # 最大连接数
修改后需要重启MySQL服务。
4. 使用连接池
对于频繁连接/断开的应用程序,使用连接池可以减少连接建立的开销:
from pymysql import pool
# 创建连接池
db_pool = pool.ConnectionPool(
size=5,
host='your_host',
user='your_username',
password='your_password',
database='your_database',
connect_timeout=30
)
# 从连接池获取连接
connection = db_pool.connection()
5. 自动重连机制
import pymysql
import time
def get_connection(max_retries=3, retry_delay=5):
retries = 0
while retries < max_retries:
try:
return pymysql.connect(
host='your_host',
user='your_username',
password='your_password',
database='your_database',
connect_timeout=30
)
except pymysql.OperationalError as e:
retries += 1
if retries == max_retries:
raise
time.sleep(retry_delay)
# 使用
connection = get_connection()
6. 检查MySQL服务器负载
高负载可能导致连接缓慢或失败:
检查MySQL服务器CPU、内存使用情况
检查是否有长时间运行的查询阻塞了连接
7. 使用SSH隧道(如果MySQL在远程)
对于远程MySQL服务器,网络延迟可能导致连接超时,可以考虑使用SSH隧道:
import pymysql
import sshtunnel
with sshtunnel.SSHTunnelForwarder(
('ssh_host', 22),
ssh_username='ssh_username',
ssh_password='ssh_password',
remote_bind_address=('mysql_host', 3306)
) as tunnel:
connection = pymysql.connect(
host='127.0.0.1',
port=tunnel.local_bind_port,
user='mysql_username',
password='mysql_password',
database='mysql_database'
)
# 执行查询...
通过以上方法,应该能够解决大多数PyMySQL连接超时的问题。根据你的具体环境选择适合的解决方案。
更多推荐



所有评论(0)