Mysql python:sqlalchemy-如何使用新的事件系统确保连接不过时
我正在使用python中的sqlalchemy包。在对现有表执行自动加载后,有一个操作需要一些时间才能执行。当我尝试使用连接时,这会导致以下错误:Mysql python:sqlalchemy-如何使用新的事件系统确保连接不过时,mysql,sqlalchemy,database-connection,operationalerror,Mysql,Sqlalchemy,Database Connection,Operationalerror,我正在使用python中的sqlalchemy包。在对现有表执行自动加载后,有一个操作需要一些时间才能执行。当我尝试使用连接时,这会导致以下错误: sqlalchemy.exc.OperationalError: (OperationalError) (2006, 'MySQL server has gone away') 我有一个简单的实用程序函数,可以执行多个插入: def insert_数据(数据插入,表格名称): 引擎=创建引擎('mysql://blah:blah123@localh
sqlalchemy.exc.OperationalError: (OperationalError) (2006, 'MySQL server has gone away')
我有一个简单的实用程序函数,可以执行多个插入:
def insert_数据(数据插入,表格名称):
引擎=创建引擎('mysql://blah:blah123@localhost/dbname')
#元数据是一个表目录。
元数据=元数据()
table=table(table\u名称、元数据、autoload=True、autoload\u with=engine)
对于mytable.c中的c:
打印c
column_names=tuple(mytable.c中c的c.name)
最终数据=[数据插入中x的dict(zip(列名称,x))]
ins=mytable.insert()
conn=引擎连接()
连接执行(ins,最终数据)
康涅狄格州关闭
由于“data_2_insert”有677161行,因此执行的时间是下一行的时间
final_data=[dict(zip(column_names,x))表示数据中的x\u 2\u insert]
我遇到了一个类似的问题。但是,我不确定如何实现robots.jpg建议的连接管理,因为robots.jpg在一篇评论中指出了这一点:
注意:对于SQLAlchemy 0.7,PoolListener不推荐使用,但是可以使用新版本实现相同的解决方案
如果有人能告诉我一些关于如何将这些建议整合到我使用sqlalchemy的方式中的建议,我将非常感激。多谢各位 我想你在寻找这样的东西:
from sqlalchemy import exc, event
from sqlalchemy.pool import Pool
@event.listens_for(Pool, "checkout")
def check_connection(dbapi_con, con_record, con_proxy):
'''Listener for Pool checkout events that pings every connection before using.
Implements pessimistic disconnect handling strategy. See also:
http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html#disconnect-handling-pessimistic'''
cursor = dbapi_con.cursor()
try:
cursor.execute("SELECT 1") # could also be dbapi_con.ping(),
# not sure what is better
except exc.OperationalError, ex:
if ex.args[0] in (2006, # MySQL server has gone away
2013, # Lost connection to MySQL server during query
2055): # Lost connection to MySQL server at '%s', system error: %d
# caught by pool, which will retry with a new connection
raise exc.DisconnectionError()
else:
raise
如果希望有条件地触发此策略,应避免在此处使用decorator,而是使用listen()
函数注册侦听器:
# somewhere during app initialization
if config.check_connection_on_checkout:
event.listen(Pool, "checkout", check_connection)
更多信息:
check\u connection()
函数<代码>事件。侦听decorator应自动注册事件处理程序,因此无需更改insert\u data()
。您可以将日志添加到check\u connection()
以确保它被调用。顺便问一下,您可以测量生成最终\u数据列表所需的时间吗?这需要54秒,实际上还不错。连接应保持打开状态。我认为问题在于最终数据太大。我有650000行10列。我认为insert语句不能处理这个问题。我将把最终的_数据写入一个csv文件,然后使用文件中的load table inline填充数据库。这就是说,我仍然需要使用此脚本在每天结束时有新数据可用时保持数据库的最新状态。每日数据的最终_数据的大小很小(最多约500行)。所以这应该行得通。为了安全,我将实施您的解决方案。