物流网络的概念,搜索引擎优化课程,网站seo价格,做淘客的网站关键词有哪些后台服务在运行时发现一个问题#xff0c;运行约15分钟后#xff0c;接口请求报错pymysql.err.InterfaceError: (0, )这个错误提示一般发生在将None赋给多个值#xff0c;定位问题时发现pymysql.err.OperationalError: (2013, Lost connection to MySQL server during query…后台服务在运行时发现一个问题运行约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 databaseself.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类型的字典cursorclasscursor()使用的种类默认值为MySQLdb.cursors.Cursorcompress启用协议压缩功能named_pipe在windows中与一个命名管道相连接init_command一旦连接建立就为数据库服务器指定一条语句来运行read_default_file使用指定的MySQL配置文件read_default_group读取的默认组unix_socket在unix中连接使用的套接字默认使用TCPport指定数据库服务器的连接端口默认是3306connection对象支持的方法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 输出如下抛出异常重新connect是不行的因为connections 仍存在未失效找到一种方法可以解决问题在每次连接之前判断该链接是否有效pymysql提供的接口是 Connection.ping()这个该方法的源码def ping(self, reconnectTrue):Check if the server is aliveif self._sock is None:if reconnect:self.connect()reconnect Falseelse: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 pymysqlclass 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()以上就是本文的全部内容希望对大家的学习有所帮助也希望大家多多支持。