2013-05-02 76 views
9

错误OperationalError: (OperationalError) (2006, 'MySQL server has gone away')我已经收到了这个错误,当我在烧瓶上编码的项目,但我不明白为什么我得到这个错误。SQLAlchemy错误MySQL服务器已经消失

我有代码(是的,如果代码小,执行速度快,则没有错误),这样\

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

这代码返回我的错误'MySQL server has gone away',但一段时间后返回它,当我使用暂停在我的脚本。

从openserver.ru使用的Mysql(它是像wamp这样的Web服务器)。

谢谢..

+2

[MySQL服务器已经消失]的文档(https://dev.mysql.com/doc/refman/5.0/en/gone-away.html)。 – timss 2013-05-02 15:28:26

+0

我认为,我得到这个错误,因为我的脚本中有逻辑错误... – 2013-05-02 16:14:03

+0

我认为当发生这种情况时,您必须重新创建引擎或会话制作者,但我仍在调查。 – Milimetric 2013-07-22 14:39:24

回答

12

的SQLAlchemy现在有关于如何使用ping命令是悲观的连接的新鲜度有很大写了:

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

从那里,

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

并进行测试以确保上述工作:

from sqlalchemy import create_engine 
e = create_engine("mysql://scott:[email protected]/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

你真棒,谢谢! – Will 2013-08-28 08:08:05

+3

我真的不喜欢没有评论的人投票。 SO应该真的需要评论下来的票... – Milimetric 2015-11-19 16:46:07

0

documentation您可以使用pool_recycle参数:

from sqlalchemy import create_engine 
e = create_engine("mysql://scott:[email protected]/test", pool_recycle=3600) 
+0

[OP](https://stackoverflow.com/q/16341911/110488)已经在使用这个参数。 – 2017-06-01 09:08:06

0

我刚刚遇到了同样的问题,这是解决了一些努力。希望我的经验对别人有帮助。

小心一些建议,我用连接池并设置pool_recycle小于wait_timeout,但它仍然不起作用。

然后,我意识到全局会话可能只是使用相同的连接和连接池不起作用。为避免全局会话,每个请求都会生成一个新的会话,处理后会被删除Session.remove()

最后,一切都很好。

相关问题