Benjamin

静以修身,俭以养德,非澹薄无以明志,非宁静无以致远。
随笔 - 386, 文章 - 0, 评论 - 196, 引用 - 0
数据加载中……

MySQLdb._exceptions.OperationalError: (2006, 'MySQL server has gone away')解决方法

一、查询mysql的show variables like “%timeout%”;interactive_timeout服务器关闭交互式连接前等待活动的秒数 参数默认值:28800秒(8小时)
在配置文件my.cnf中只设置参数interactive_timeout=100或者设置一个比较大的值,则重启服务器后进入或者set global interactive_timeout=28800;重启mysql服务器
注:
从文档上来看wait_timeout和interactive_timeout都是指不活跃的连接超时时间,连接线程启动的时候wait_timeout会根据是交互模式还是非交互模式被设置为这两个值中的一个。
如果我们运行mysql -uroot -p命令登陆到mysql,wait_timeout就会被设置为interactive_timeout的值。如果我们在wait_timeout时间内没有进行任何操作,那么再次操作的时候就会提示超时,这是mysql client会重新连接。
interactive_timeout和wait_timeout在连接空闲阶段(sleep)起作用,对于保持sleep状态超过了wait_timeout(或interactive_timeout,取决于CLIENT_INTERACTIVE标志)的客户端,MySQL会主动断开连接。
可以用set命令或在my.cnf文件中设置,设置后需要重启数据库
二、conn = None
def _conn():  # 连接带异常处理
    try:
        global conn
        conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="xhaccount", port=3306,
                               charset="utf8")  # 连接对象
        return True
    except Exception as e:
        print("str(Exception):\t", str(e))
        print("str(e):\t\t", str(e))
        print("repr(e):\t", repr(e))
        # Get information about the exception that is currently being handled
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print('e.message:\t', exc_value)
        print("Note, object e and exc of Class %s is %s the same." %
              (type(exc_value), ('not', '')[exc_value is e]))
        print('traceback.print_exc(): ', traceback.print_exc())
        return False
def _reConn():  # 重试连接
    try:
        conn.ping()  # 校验连接是否异常
    except Exception as e:
        if _conn() is True:  # 重新连接,成功退出
            return
        print("str(Exception):\t", str(e))
        print("str(e):\t\t", str(e))
        print("repr(e):\t", repr(e))
        # Get information about the exception that is currently being handled
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print('e.message:\t', exc_value)
        print("Note, object e and exc of Class %s is %s the same." %
              (type(exc_value), ('not', '')[exc_value is e]))
        print('traceback.print_exc(): ', traceback.print_exc())
        print('重连失败!!!!!!!')
每次执行sql语句的时候,调用下_reConn()

posted on 2020-12-30 09:44 Benjamin 阅读(2162) 评论(0)  编辑 收藏 引用 所属分类: python


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理