Mysql fetchall 方法抛出“发现未读结果”异常
我正在用一个Python脚本对Mysql执行查询。我使用的是Anaconda版本的Python,并且安装了Oracle的Mysql模块。如果我把查询限制在大约500行数据,它可以顺利执行。但如果超过这个数量,就会出现“发现未读结果”的异常。我不太明白自己哪里出错了。希望能得到一些帮助。以下是我的代码:
import mysql.connector
import csv
cnx = mysql.connector.connect(user='user', password='password',
host='server',
port='3306',
database='db',
connect_timeout=2000,
buffered=True)
try:
query = "...large query that returns > 500 records..."
cursor = cnx.cursor()
cursor.execute(query)
print 'this will print'
results = cursor.fetchall()
print 'this will not print'
with open("data.csv", "wb") as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerows(results)
finally:
cursor.close()
cnx.close()
1 个回答
0
看起来你在内存中缓存数据时,内存不够用了,所以你的程序被强制关闭了。建议你使用流式结果集来代替这种方式(可以用 MySQLdb.cursors.SSCursor)。
cnx = MySQLdb.connector.connect(user='user', password='password',
host='server',
port='3306',
database='db',
connect_timeout=2000,
buffered=True)
try:
query = "...large query that returns > 500 records..."
cursor = MySQLdb.SSCursor(conn)
#cursor = cnx.cursor()
cursor.execute(query)
..