SQLAlchemy error MySQL server has gone away

前端 未结 6 2171
清酒与你
清酒与你 2021-02-05 07:58

Error OperationalError: (OperationalError) (2006, \'MySQL server has gone away\') i\'m already received this error when i coded project on Flask, but i cant underst

6条回答
  •  無奈伤痛
    2021-02-05 08:51

    Looking at the mysql docs, we can see that there are a bunch of reasons why this error can occur. However, the two main reasons I've seen are:


    1) The most common reason is that the connection has been dropped because it hasn't been used in more than 8 hours (default setting)

    By default, the server closes the connection after eight hours if nothing has happened. You can change the time limit by setting the wait_timeout variable when you start mysqld

    I'll just mention for completeness the two ways to deal with that, but they've already been mentioned in other answers:

    A: I have a very long running job and so my connection is stale. To fix this, I refresh my connection:

    create_engine(conn_str, pool_recycle=3600)  # recycle every hour
    

    B: I have a long running service and long periods of inactivity. To fix this I ping mysql before every call:

    create_engine(conn_str, pool_pre_ping=True)
    

    2) My packet size is too large, which should throw this error:

    _mysql_exceptions.OperationalError: (1153, "Got a packet bigger than 'max_allowed_packet' bytes")
    

    I've only seen this buried in the middle of the trace, though often you'll only see the generic _mysql_exceptions.OperationalError (2006, 'MySQL server has gone away'), so it's hard to catch, especially if logs are in multiple places.

    The above doc say the max packet size is 64MB by default, but it's actually 16MB, which can be verified with SELECT @@max_allowed_packet

    To fix this, decrease packet size for INSERT or UPDATE calls.

提交回复
热议问题