2014-06-18 131 views
2

我播種後在MySQL服務器已消失(代碼2006)

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') 

回答

8

與數據庫的連接已關閉,因爲它已空閒太久。從回溯看來,您似乎在交互式地進行查詢。如果你知道你已經閒置超過5分鐘,你應該這樣做:

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

這是關於該主題最直接的答案(包括其他問題),但是我會注意到,在做一個非常大的delete()時,Django會斷開這個跟蹤回溯。 – WAF

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()允許恢復的連接是可能的,而不是總是關閉連接時。

相關問題