mysql 斷開連接解決方法 (2013, 'Lost connection to MySQL server during query') (mysql have gone away)


1,出現該問題的原因,代碼里導入了mysql的一個連接,但是長時間沒有操作,超過了mysql的awiat_timeout 時間(默認8小時)

 

2,解決思路:

  1,修改mysql 的await_timeout (不建議)

  2,django 中使用 close_old_connections()  關閉舊的連接  (from django.db import close_old_connections)  

    (該方法一般在django 的腳本中使用)

from django.db import close_old_connections

def index():
    close_old_connections()
    s = Student.objects.all()

  3,django 的視圖函數中使用可以定義中間件 (請求開始時連接,請求結束后斷開) (使用的可能性不大)

# middleware.py
from my_blog.db import database  
# Import the peewee database instance.


def PeeweeConnectionMiddleware(get_response):
    def middleware(request):
        database.connect()
        try:
            response = get_response(request)
        finally:
            if not database.is_closed():
                database.close()
        return response
    return middleware
View Code

  4,flask 中解決思路:和django中一樣,在請求來時連接,在請求結束后斷開

# app.py
from bottle import hook  #, route, etc, etc.
from peewee import *

db = SqliteDatabase('my-bottle-app.db')

@hook('before_request')
def _connect_db():
    db.connect()

@hook('after_request')
def _close_db():
    if not db.is_closed():
        db.close()

# Rest of your bottle app goes here.
View Code

   5,如果是使用peewee ,在模型類連接時修改繼承類,后面正常使用就ok  (可能性比較大)

from peewee import *
from peewee import __exception_wrapper__

class RetryOperationalError(object):
    def execute_sql(self, sql, params=None, commit=True):
        try:
            cursor = super(RetryOperationalError, self).execute_sql(sql, params, commit)
        except OperationalError:
            if not self.is_closed():
                self.close()
            with __exception_wrapper__:
                cursor = self.cursor()
                cursor.execute(sql, params or ())
                if commit and not self.in_transaction():
                    self.commit()
        return cursor


class RetryMySQLDatabase(RetryOperationalError, MySQLDatabase):
    pass


database = RetryMySQLDatabase('sql_test', **{'charset': 'utf8', 'sql_mode': 'PIPES_AS_CONCAT', 'use_unicode': True, 'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': 'mysql'})

class UnknownField(object):
    def __init__(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = database

class Teacher(BaseModel):
    depart = CharField()
    prof = CharField(null=True)
    tbirthday = DateTimeField(null=True)
    tname = CharField()
    tno = CharField(primary_key=True)
    tsex = CharField()

    class Meta:
        table_name = 'teacher'

class Course(BaseModel):
    cname = CharField()
    cno = CharField()
    tno = ForeignKeyField(column_name='tno', field='tno', model=Teacher)

    class Meta:
        table_name = 'course'

class DjangoMigrations(BaseModel):
    app = CharField()
    applied = DateTimeField()
    name = CharField()

    class Meta:
        table_name = 'django_migrations'

class Emp(BaseModel):
    deptno = CharField(null=True)
    duty = CharField(null=True)
    empid = AutoField()
    name = CharField(null=True)
    sal = CharField(null=True)

    class Meta:
        table_name = 'emp'
View Code

  6,tornado 解決方法如下

from tornado.web import RequestHandler

db = SqliteDatabase('my_db.db')

class PeeweeRequestHandler(RequestHandler):
    def prepare(self):
        db.connect()
        return super(PeeweeRequestHandler, self).prepare()

    def on_finish(self):
        if not db.is_closed():
            db.close()
        return super(PeeweeRequestHandler, self).on_finish()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM