30

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

I have code (yeah, if code small and executing fast, then no errors) like this \

db_engine = create_engine('mysql://[email protected]/mind?charset=utf8', pool_size=10, pool_recycle=7200)
Base.metadata.create_all(db_engine)

Session = sessionmaker(bind=db_engine, autoflush=True)
Session = scoped_session(Session)
session = Session()

# there many classes and functions

session.close()

And this code returns me error 'MySQL server has gone away', but return it after some time, when i use pauses in my script.

Mysql i use from openserver.ru (it's web server like such as wamp).

Thanks..

3
  • 2
    Documentation for MySQL server has gone away.
    – timss
    May 2, 2013 at 15:28
  • i think, that i get this error because i have logic error in my script... May 2, 2013 at 16:14
  • I think you have to re-create the engine or sessionmaker when this happens, but I'm still investigating.
    – Milimetric
    Jul 22, 2013 at 14:39

6 Answers 6

26

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.

2
  • other answer great also, but you telling about "why" and it's make more helpful rather than other answer,, thanks Feb 2, 2021 at 0:28
  • Could you provide details on why 1.A and 1.B should be handled differently? Shouldn't it be enough with the pool recycle for both?
    – diegobatt
    Oct 7 at 14:28
20

SQLAlchemy now has a great write-up on how you can use pinging to be pessimistic about your connection's freshness:

http://docs.sqlalchemy.org/en/latest/core/pooling.html#disconnect-handling-pessimistic

From there,

from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy.pool import Pool

@event.listens_for(Pool, "checkout")
def ping_connection(dbapi_connection, connection_record, connection_proxy):
    cursor = dbapi_connection.cursor()
    try:
        cursor.execute("SELECT 1")
    except:
        # optional - dispose the whole pool
        # instead of invalidating one at a time
        # connection_proxy._pool.dispose()

        # raise DisconnectionError - pool will try
        # connecting again up to three times before raising.
        raise exc.DisconnectionError()
    cursor.close()

And a test to make sure the above works:

from sqlalchemy import create_engine
e = create_engine("mysql://scott:tiger@localhost/test", echo_pool=True)
c1 = e.connect()
c2 = e.connect()
c3 = e.connect()
c1.close()
c2.close()
c3.close()

# pool size is now three.

print "Restart the server"
raw_input()

for i in xrange(10):
    c = e.connect()
    print c.execute("select 1").fetchall()
    c.close()
0
2

from documentation you can use pool_recycle parameter:

from sqlalchemy import create_engine
e = create_engine("mysql://scott:tiger@localhost/test", pool_recycle=3600)
1
  • The OP is already using this parameter.
    – Chen Levy
    Jun 1, 2017 at 9:08
2

I just faced the same problem, which is solved with some effort. Wish my experience be helpful to others.

Fallowing some suggestions, I used connection pool and set pool_recycle less than wait_timeout, but it still doesn't work.

Then, I realized that global session maybe just use the same connection and connection pool didn't work. To avoid global session, for each request generate a new session which is removed by Session.remove() after processing.

Finally, all is well.

0

One more point to keep in mind is to manually push the flask application context with database initialization. This should resolve the issue.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

app = Flask(__name__)
with app.app_context():
    db.init_app(app)
-2

https://docs.sqlalchemy.org/en/latest/core/pooling.html#disconnect-handling-optimistic

 def sql_read(cls, sql, connection):
    """sql for read action like select
    """
    LOG.debug(sql)
    try:
        result = connection.engine.execute(sql)
        header = result.keys()
        for row in result:
            yield dict(zip(header, row))
    except OperationalError as e:
        LOG.info("recreate pool duo to %s" % e)
        connection.engine.pool.recreate()
        result = connection.engine.execute(sql)
        header = result.keys()
        for row in result:
            yield dict(zip(header, row))
    except Exception as ee:
        LOG.error(ee)
        raise SqlExecuteError()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.