Mysql fetchall方法抛出"发现未读结果"例外

时间:2014-10-24 04:46:03

标签: python mysql

我正在从python脚本执行一个针对Mysql的查询。我正在使用带有Oracle Mysql模块的anaconda分发的python。如果我将查询限制为~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 :(得分: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)
 ..