MySQL服务器已经消失(代码2006)

时间:2014-06-18 19:57:26

标签: mysql django

我播种

How to enable MySQL client auto re-connect with MySQLdb?

我有同样的问题,我使用pythonanywhere.com,当我写p.save()时,我有如下错误。

它说明了更新mysql以修复它,但我不知道需要编写哪些代码或shell命令。

你能帮助我吗?

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/daro822/.virtualenvs/django16/local/lib/python2.7/site-packages/django/db/models/base.py", line 545, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/daro822/.virtualenvs/django16/local/lib/python2.7/site-packages/django/db/models/base.py", line 570, in save_base
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
  File "/home/daro822/.virtualenvs/django16/local/lib/python2.7/site-packages/django/db/transaction.py", line 280, in __enter__
    connection.set_autocommit(False)
  File "/home/daro822/.virtualenvs/django16/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 340, in set_autocommit
    self._set_autocommit(autocommit)
  File "/home/daro822/.virtualenvs/django16/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 461, in _set_autocommit
    self.connection.autocommit(autocommit)
  File "/home/daro822/.virtualenvs/django16/local/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/daro822/.virtualenvs/django16/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 461, in _set_autocommit
    self.connection.autocommit(autocommit)
  File "/home/daro822/.virtualenvs/django16/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 243, in autocommit
    _mysql.connection.autocommit(self, on)
OperationalError: (2006, 'MySQL server has gone away')

2 个答案:

答案 0 :(得分:8)

您与数据库的连接已关闭,因为它闲置时间过长。从追溯,看起来您正在以交互方式进行查询。如果你知道你已经闲置超过5分钟,你应该这样做:

from django.db import connection; connection.close()

答案 1 :(得分:2)

我解决了插入此代码时需要恢复和刷新连接的问题:

        try:
            cursor = connections['default'].cursor()
            db = cursor.db
            assert issubclass(db.__class__, BaseDatabaseWrapper)
            if db.connection is None or not db.is_usable():
                db.close_if_unusable_or_obsolete()
                with db.wrap_database_errors:
                    db.connect()
                logger.info('Restoring the Mysql Connection')
        except Exception as e:
            logger.exception('DB Connection error')

请注意我使用connections['default']因为我配置了多个数据库,因此您可以设置特定连接,另请注意我使用db.is_usable()以便调用.ping()以允许恢复可能的连接,而不是始终关闭连接。