我有一個巨大的表,我需要處理其中的所有行。我總是得到這個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