【发布时间】:2010-12-25 11:39:49
【问题描述】:
我有一个巨大的表,我需要处理其中的所有行。我总是收到这个丢失的连接消息,我无法重新连接并将光标恢复到它的最后一个位置。这基本上是我在这里的代码:
#
import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb.connect('hostname', 'user', '*****', 'some_table', cursorclass=MySQLdb.cursors.SSCursor)
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
#
#
db = DB()
sql = "SELECT bla FROM foo"
data = db.query(sql)
for row in data:
do_something(row)
#
但我总是得到这个:
#
Traceback (most recent call last):
File "teste.py", line 124, in <module>
run()
File "teste.py", line 109, in run
for row in data:
File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 417, in next
row = self.fetchone()
File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 388, in fetchone
r = self._fetch_row(1)
File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 285, in _fetch_row
return self._result.fetch_row(size, self._fetch_type)
_mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')
Exception _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') in <bound method SSCursor.__del__ of <MySQLdb.cursors.SSCursor object at 0x7f7e3c8da410>> ignored
#
你有什么想法吗?
【问题讨论】:
-
从 connect() 调用中删除“cursorclass=MySQLdb.cursors.SSCursor”就足够了。它现在工作得很好。谢谢。
-
我遇到了同样的问题,但是我有大约 1B 行数据,所以我想使用 SSCursor 在 mysqld 端而不是我的 python 应用程序上缓存查询的数据。将 net_write_timeout 扩大到 1 小时解决了这个问题 :)
-
致从 Google 来到这里的人们:如果您使用多线程,则需要为每个线程提供自己的连接。