查詢期間與MySQL服務(wù)器的連接丟失我有一個(gè)巨大的表,我需要處理其中的所有行。我總是得到這個(gè)丟失的連接消息,我無(wú)法重新連接并將光標(biāo)恢復(fù)到它的最后位置。這基本上就是我在這里的代碼:#import MySQLdbclass 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)#但我總是得到這個(gè):#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#你有什么主意嗎?
3 回答

HUWWW
TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
擴(kuò)展mysql服務(wù)器的max_allowed_packet有三種方法:
更改mysql服務(wù)器計(jì)算機(jī)上的
max_allowed_packet=64M
文件/etc/mysql/my.cnf
并重新啟動(dòng)服務(wù)器在mysql服務(wù)器上執(zhí)行sql:
set global max_allowed_packet=67108864;
Python連接到mysql后執(zhí)行sql:
connection.execute('set max_allowed_packet = 67108864')

互換的青春
TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
確保在連接前關(guān)閉光標(biāo)。我用這個(gè)解決了我的問(wèn)題:
if cur and con: cur.close() con.close()
添加回答
舉報(bào)
0/150
提交
取消