python - 大型查询后 psycopg2 泄漏内存

标签 python postgresql psycopg2

我正在使用 psycopg2(我升级到版本 2.5)在 python 脚本中针对我的 postgres 数据库运行大型查询。查询完成后,我关闭游标和连接,甚至运行gc,但该过程仍然消耗大量内存(确切地说是7.3gb)。我错过了清理步骤吗?

import psycopg2
conn = psycopg2.connect("dbname='dbname' user='user' host='host'")
cursor = conn.cursor()
cursor.execute("""large query""")
rows = cursor.fetchall()
del rows
cursor.close()
conn.close()
import gc
gc.collect()

最佳答案

我遇到了类似的问题,经过几个小时的血汗和泪水,我发现答案只需要添加一个参数。

代替

cursor = conn.cursor()

cursor = conn.cursor(name="my_cursor_name")

或者更简单的

cursor = conn.cursor("my_cursor_name")

详情见http://initd.org/psycopg/docs/usage.html#server-side-cursors

我发现说明有点困惑,因为我需要重写我的 SQL 以包含 “DECLARE my_cursor_name ....”然后是“FETCH count 2000 FROM my_cursor_name”,但事实证明,如果您在创建游标时简单地覆盖“name=None”默认参数,psycopg 会在后台为您完成这一切。

上述使用 fetchone 或 fetchmany 的建议并不能解决问题,因为如果您未设置 name 参数,psycopg 将默认尝试将整个查询加载到 ram 中。您可能需要做的唯一另一件事(除了声明名称参数)是将 cursor.itersize 属性从默认的 2000 更改为 1000,如果您的内存仍然太少。

关于python - 大型查询后 psycopg2 泄漏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17199113/

相关文章:

performance - PostgreSql 使用 IN statemente 性能非常慢

python - psycopg2 - 具有多个未提交的插入语句的函数

python - 如何使用 psycopg2 以编程方式获取表结构

python - 如何最好地处理这个 Python 数值错误?

python - 下一个(h) TypeError : 'int' object is not an iterator

postgresql - ServiceStack Ormlite - Postgres 使用 MaxDate 将 Date 属性序列化为 JsonB

python - 如何从 psycopg2 中的查询保存 CSV 文件

python - 找出所有的方法来决定 list 分为三

python - 不显示所有数字的 Django 分页器页面范围

postgresql - 替代已弃用的 PostgresDataType.JSON?