数据库断开连接mysql has gone away

本文探讨了在使用Python2.7+Django1.8时遇到的MySQL“mysqlhasgoneaway”错误,分析了连接超时的原因,并提供了一个通过修改Django源码来检查并关闭无效连接的方法,实测对效率影响较小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用python2.7+django1.8时,Mysql报错 “mysql has gone away”,查看了其他博客后得知是因为连接超时,而且都有下面这种方法,少有人提到效率的问题,而效率是不得不考虑的事情(我们写操作比较多 mysql连接 平时都是没有问题的 但是一到周末就GG),所以亲自测一下

from django.db.backends.base.base import BaseDatabaseWrapper
import time


def close_old_connections():
    for conn in connections.all():
        conn.close_if_unusable_or_obsolete()


def close_if_unusable_or_obsolete(self):
    """
    Closes the current connection if unrecoverable errors have occurred,
    or if it outlived its maximum age.
    """
    if self.connection is not None:
        # If the application didn't restore the original autocommit setting,
        # don't take chances, drop the connection.
        if self.get_autocommit() != self.settings_dict['AUTOCOMMIT']:
            LOG.warning('mysql connect close !!!!!')
            self.close()
            return
        else:
            LOG.warning('mysql has ckeck but do nothing !!!!!')


        # If an exception other than DataError or IntegrityError occurred
        # since the last commit / rollback, check if the connection works.
        if self.errors_occurred:
            if self.is_usable():
                self.errors_occurred = False
            else:
                self.close()
                return

        if self.close_at is not None and time.time() >= self.close_at:
            self.close()
            return

BaseDatabaseWrapper.close_if_unusable_or_obsolete = close_if_unusable_or_obsolete

经过加上日志信息后发现,如果连接是正常的不会做任何事情,如果连接是无效的,会关闭旧连接,新建一个,对效率的影响不是很大,可以直接在经常报错的地方前面添加。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值