python mysql断开重连的实现方法

后台服务在运行时发现一个问题,运行约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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • MySQL-Python安装问题小记

    安装完mysql-python后import加载模块提示以下错误, 复制代码 代码如下: ImportError: libmysqlclient_r.so.16: cannot open shared object file: No such file or directory 于是google之,总结一下解决方法: (1)在mysql-ython的安装目录下找到site.cfg,将 #mysql_config = XXXXXXXXXXXXXXXX 注释符号去掉,并填上mysql_config的

  • python中MySQLdb模块用法实例

    本文实例讲述了python中MySQLdb模块用法.分享给大家供大家参考.具体用法分析如下: MySQLdb其实有点像php或asp中连接数据库的一个模式了,只是MySQLdb是针对mysql连接了接口,我们可以在python中连接MySQLdb来实现数据的各种操作. python连接mysql的方案有oursql.PyMySQL. myconnpy.MySQL Connector 等,不过本篇要说的确是另外一个类库MySQLdb,MySQLdb 是用于Python链接Mysql数据库的接口,它

  • Python操作Mysql实例代码教程在线版(查询手册)

    实例1.取得MYSQL的版本在windows环境下安装mysql模块用于python开发 MySQL-python Windows下EXE安装文件下载 复制代码 代码如下: # -*- coding: UTF-8 -*- #安装MYSQL DB for pythonimport MySQLdb as mdb con = None try:    #连接mysql的方法:connect('ip','user','password','dbname')    con = mdb.connect('l

  • python使用mysqldb连接数据库操作方法示例详解

    复制代码 代码如下: # -*- coding: utf-8 -*- #mysqldb    import time, MySQLdb #连接    conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")  cursor = conn.cursor() #写入    sql = "i

  • Python中操作mysql的pymysql模块详解

    前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持3.x版本. 本文测试python版本:2.7.11.mysql版本:5.6.24 一.安装 pip3 install pymysql 二.使用操作 1.执行SQL #!/usr/bin/env pytho # -*- coding:utf-8 -*- import pymysql # 创建连接 conn = pymysql.connect(host=

  • python操作mysql中文显示乱码的解决方法

    本文实例展示了一个脚本python用来转化表配置数据xml并生成相应的解析代码. 但是在中文编码上出现了乱码,现将解决方法分享出来供大家参考. 具体方法如下: 1. Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8) 2. MySQL数据库charset=utf-8 3. Python连接MySQL是加上参数 charset=utf8 4. 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8) 示例代码如下:

  • 使用Python操作MySQL的一些基本方法

    前奏 为了能操作数据库, 首先我们要有一个数据库, 所以要首先安装Mysql, 然后创建一个测试数据库python_test用以后面的测试使用 CREATE DATABASE `python_test` CHARSET UTF8 导入数据库模块 import MySQLdb 连接数据库 con = MySQLdb.connect(host="localhost", user="root", passwd="******",db="pyt

  • python Django连接MySQL数据库做增删改查

    1.下载安装MySQLdb类库http://www.djangoproject.com/r/python-mysql/2.修改settings.py 配置数据属性 复制代码 代码如下: DATABASES = {    'default': {        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.        'NAME': 'djang

  • Python如何读取MySQL数据库表数据

    本文实例为大家分享了Python读取MySQL数据库表数据的具体代码,供大家参考,具体内容如下 环境:Python 3.6 ,Window 64bit 目的:从MySQL数据库读取目标表数据,并处理 代码: # -*- coding: utf-8 -*- import pandas as pd import pymysql ## 加上字符集参数,防止中文乱码 dbconn=pymysql.connect( host="**********", database="kimbo&

  • Python下的Mysql模块MySQLdb安装详解

    默认情况下,MySQLdb包是没有安装的,不信? 看到类似下面的代码你就信了. 复制代码 代码如下: -bash-3.2# /usr/local/python2.7.3/bin/python get_cnblogs_news.py Traceback (most recent call last):  File "get_cnblogs_news.py", line 9, in <module>    import MySQLdbImportError: No module

  • 用 Python 连接 MySQL 的几种方式详解

    尽管很多 NoSQL 数据库近几年大放异彩,但是像 MySQL 这样的关系型数据库依然是互联网的主流数据库之一,每个学 Python 的都有必要学好一门数据库,不管你是做数据分析,还是网络爬虫,Web 开发.亦或是机器学习,你都离不开要和数据库打交道,而 MySQL 又是最流行的一种数据库,这篇文章介绍 Python 操作 MySQL 的几种方式,你可以在实际开发过程中根据实际情况合理选择. 1.MySQL-python MySQL-python 又叫 MySQLdb,是 Python 连接 M

随机推荐