python mysql断开重连的实现方法
作者:sysu_lluozh 时间:2024-01-24 01:20:26
后台服务在运行时发现一个问题,运行约15分钟后,接口请求报错
pymysql.err.InterfaceError: (0, '')
这个错误提示一般发生在将None赋给多个值,定位问题时发现
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')
如何解决这个问题呢
出现问题的代码
class MysqlConnection(object):
"""
mysql操作类,对mysql数据库进行增删改查
"""
def __init__(self, config):
# Connect to the database
self.connection = pymysql.connect(**config)
self.cursor = self.connection.cursor()
def Query(self, sql):
"""
查询数据
:param sql:
:return:
"""
self.cursor.execute(sql)
return self.cursor.fetchall()
在分析问题前,先看看Python 数据库的Connection、Cursor两大对象
Python 数据库图解流程
Connection、Cursor形象比喻
Connection()的参数列表
host,连接的数据库服务器主机名,默认为本地主机(localhost)
user,连接数据库的用户名,默认为当前用户
passwd,连接密码,没有默认值
db,连接的数据库名,没有默认值
conv,将文字映射到Python类型的字典
cursorclass,cursor()使用的种类,默认值为MySQLdb.cursors.Cursor
compress,启用协议压缩功能
named_pipe,在windows中,与一个命名管道相连接
init_command,一旦连接建立,就为数据库服务器指定一条语句来运行
read_default_file,使用指定的MySQL配置文件
read_default_group,读取的默认组
unix_socket,在unix中,连接使用的套接字,默认使用TCP
port,指定数据库服务器的连接端口,默认是3306
connection对象支持的方法
Cursor对象支持的方法
用于执行查询和获取结果
execute方法:执行SQL,将结果从数据库获取到客户端
调试代码,将超时时间设置较长
self.connection._write_timeout = 10000
发现并没有生效
使用try...except...
方法捕获失败后重新连接数据库
try:
self.cursor.execute(sql)
except:
self.connection()
self.cursor.execute(sql)
直接抛出异常,并没有执行except代码段
打印self.connection
,输出如下:
<pymysql.connections.Connection object at 0x0000000003E2CCC0>
抛出异常重新connect是不行的,因为connections
仍存在未失效
找到一种方法可以解决问题,在每次连接之前,判断该链接是否有效,pymysql提供的接口是 Connection.ping()
这个该方法的源码
def ping(self, reconnect=True):
"""Check if the server is alive"""
if self._sock is None:
if reconnect:
self.connect()
reconnect = False
else:
raise err.Error("Already closed")
try:
self._execute_command(COMMAND.COM_PING, "")
return self._read_ok_packet()
except Exception:
if reconnect:
self.connect()
return self.ping(False)
else:
raise
在每次请求数据库前执行如下代码
def reConnect(self):
try:
self.connection.ping()
except:
self.connection()
不过这样的方式虽然能解决问题,但是感觉相对较low,希望有更好的处理方法
目前已实现的数据库查询这部分的代码
import pymysql
class DBManager(object):
def __init__(self,config):
self.connection = pymysql.connect(**config) # config为数据库登录验证配置信息
self.cursor = self.connection.cursor()
def query(self, sql, params):
try:
with self.connection.cursor() as cursor:
cursor.execute(sql, params)
result = cursor.fetchall()
self.connection.commit()
return result
# self.connection.close()
except Exception as e:
traceback.print_exc()
来源:https://blog.csdn.net/lluozh2015/article/details/78411884
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JavaScript使用正则表达式获取全部分组内容的方法示例
![](https://img.aspxhome.com/file/2023/4/56214_0s.png)
JSP EL表达式详细介绍
![](https://img.aspxhome.com/file/2023/9/97899_0s.jpg)
python中super()函数的理解与基本使用
![](https://img.aspxhome.com/file/2023/0/65520_0s.png)
Linux CentOS Python开发环境搭建教程
ASP Session对象的集合以及属性方法事件
python socket模块创建和使用套接字示例详解
pandas分别写入excel的不同sheet方法
Python面向对象编程基础解析(一)
Python基于Webhook实现github自动化部署
![](https://img.aspxhome.com/file/2023/2/77752_0s.jpg)
python实现矩阵和array数组之间的转换
如何保持Oracle数据库的优良性能
pytorch MSELoss计算平均的实现方法
浅谈编码,解码,乱码的问题
![](https://img.aspxhome.com/file/2023/0/120960_0s.jpg)
Oracle 9i产品文档
如何解决从文本文件中调出记录出现丢失换行的问题?
如何安装MySQL Community Server 5.6.39
![](https://img.aspxhome.com/file/2023/3/121593_0s.jpg)
Vue ElementUI之Form表单验证遇到的问题
![](https://img.aspxhome.com/file/2023/1/139841_0s.png)
MySql总弹出mySqlInstallerConsole窗口的解决方法
![](https://img.aspxhome.com/file/2023/3/112893_0s.png)
pyhon如何把程序打包为whl
![](https://img.aspxhome.com/file/2023/6/60976_0s.png)
python-opencv实现视频指定帧数间隔图像的保存功能
![](https://img.aspxhome.com/file/2023/4/97224_0s.jpg)