【问题标题】:pg8000 and cursor.fetchall() failing to return records if the number of records is moderate如果记录数适中,pg8000 和 cursor.fetchall() 无法返回记录
【发布时间】:2014-09-27 01:27:02
【问题描述】:

我正在使用适配器pg8000 使用以下代码读取我的数据库中的记录:

cursor = conn.cursor()
results = cursor.execute("SELECT * from data_" + country + " WHERE date >= %s AND date <= %s AND time >= %s AND time <= %s", (datetime.date(fromdate[0], fromdate[1], fromdate[2]), datetime.date(todate[0], todate[1], todate[2]),datetime.time(fromtime[0],fromtime[1]), datetime.time(totime[0],totime[1])))
results = cursor.fetchall()

当我选择一个包含 100 条记录的日期范围时,问题就出现了。它不是大量的记录,但足以导致以下问题,我看不出问题可能来自哪里 - 因为它似乎取决于带回的记录数量。例如:results = cursor.fetchall() 似乎可以正常工作并返回一个结果。

我得到的错误信息是:

File "/mnt/opt/Centos5.8/python-2.7.8/lib/python2.7/site-packages/pg8000/core.py", line 1650, in handle_messages
    raise error
pg8000.errors.ProgrammingError: ('ERROR', '34000', 'portal "pg8000_portal_0" does not exist')

很明显,尽管进行了探索,但我找不到解决此问题的方法。

使用fetchmany()时,结果如下:

results = cursor.fetchmany(100) 作品 - 仅限于 100 个

results = cursor.fetchmany(101) 失败 - 与上述相同的错误

【问题讨论】:

  • 出于兴趣,为什么是“pg8000”? psycopg2 适配器是迄今为止得到最好支持的。
  • @CraigRinger 它的纯度很吸引人。
  • @Navonod 这令人费解,看起来像是 pg8000 中的错误。你能在github.com/mfenniak/pg8000/issues 记录这个错误,给出PostgreSQL、Python 和pg8000 的版本吗?此外,一个简短但完整的 Python 脚本可以重现该错误会很棒!
  • @TonyLocke 我认为它归结为自动提交

标签: python sql postgresql pg8000


【解决方案1】:

在自动提交模式下,您检索的行数不能超过 pg8000 缓存所保存的行数(默认为 100)。

我有 made a commit,它会在发生这种情况时提供更好的错误消息,这将在 pg8000 的下一个版本中提供。

原因是,如果一个查询返回的行数大于pg8000缓存中的行数,则数据库门户保持打开状态,然后当缓存为空时,从门户中获取更多行.门户只能存在于事务中,因此在自动提交模式下,在检索到第一批行后,门户会立即关闭。如果您尝试从门户中检索第二批,则会收到问题中报告的“门户不存在”错误。

【讨论】:

    【解决方案2】:

    看来这可以通过设置来解决:

    conn.autocommit = False
    

    现在代码如下:

    conn.autocommit = False
    cursor = conn.cursor()
    results = cursor.execute("SELECT * from data_" + country + " WHERE date >= %s AND date <= %s AND time >= %s AND time <= %s", (datetime.date(fromdate[0], fromdate[1], fromdate[2]), datetime.date(todate[0], todate[1], todate[2]),datetime.time(fromtime[0],fromtime[1]), datetime.time(totime[0],totime[1])))
    results = cursor.fetchall()
    

    我不确定为什么会这样 - 但自动提交设置为 True 时,100 条记录的数量似乎有限制

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      相关资源
      最近更新 更多