【问题标题】:Mysql fetchall method throws "Unread result found" ExceptionMysql fetchall 方法抛出“Unread result found”异常
【发布时间】:2014-10-24 04:46:03
【问题描述】:

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

【问题讨论】:

  • 这是java中的等价物: Class.forName("com.mysql.jdbc.Driver") ;连接连接 = DriverManager.getConnection("jdbc:mysql://server:3306/db", "user", "password") ;语句 stmt = conn.createStatement() ; String query = "...返回 > 500 条记录的大型查询..." ;结果集 rs = stmt.executeQuery(query);转换为CSV(rs); // 遍历结果并写入 csv

标签: python mysql


【解决方案1】:

似乎您在缓冲内存中的行时内存不足,您的进程肯定会被杀死。尝试使用流式结果集而不是那个(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)
 ..

【讨论】:

  • 刚刚发现这个帖子也指向同样的问题::stackoverflow.com/a/5994545/3378649
  • 我有 16GB 的内存。而且我没有使用 MySQLdb。
  • 这会导致同样的错误 rows = cursor.fetchmany(size=500) 而 rows: rows = cursor.fetchmany(size=500)
  • 只需使用 (Count(table)) 作为查询,通过识别您的一个表来查看整体 raws 的数量?
  • 查询返回4285行
猜你喜欢
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多