我有一个巨大的表,我需要处理其中的所有行。我总是得到这个Lost连接消息,我无法重新连接并将光标恢复到最后一个位置。这是基本的代码,我这里有:在查询过程中丢失与MySQL服务器的连接
#
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”就足够了。现在它工作得很好。谢谢。 – Otavio 2009-12-16 19:13:45
我有同样的问题,但我有〜1B行数据,所以我想使用SSCursor缓存查询数据在mysqld端而不是我的python应用程序。 扩大net_write_timeout到1小时修复问题:) – cow 2017-07-08 16:38:21