我使用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

I found the instructions a little confusing in that I though I'd need to re写 my SQL to include "DECLARE my_cursor_name ...." and then a "FETCH count 2000 FROM my_cursor_name" but it turns out psycopg does that all for you under the hood if you simply over写 the "name=None" default parameter when creating a cursor.

上面使用fetchone或fetchmany的建议并不能解决这个问题,因为如果不设置name参数,psycopg将在默认情况下try 将整个查询加载到ram中.除了声明名称参数之外,您可能还需要更改光标.如果内存仍然太少,请将属性从默认的2000设置为1000.

Postgresql相关问答推荐

优化PostgreSQL查询以将用户插入数据库

我无法让pg_cron扩展在最新的Postgres 16图像中工作

一列引用两个不同的表

如何在PostgreSQL中以行值的形式获取列

将CSV文件复制到临时表

使用jOOQ在postgres上取消嵌套enum_range

在特定距离内创建点的唯一索引

如何在plpgsql中找到一行中的最大值?

找出两个表之间的差异

如何展平也在关系中使用的区分大小写的列

如何使用 pg_dump 或 psql 从 *.sql 恢复 PostgreSQL 表?

PostgreSQL:如何安装 plpythonu 扩展

在不存在的行上有select for update块

如何在数据库表中查找重复条目?

错误:ERROR: table name specified more than once

Oracle 相当于 Postgres 的 DISTINCT ON?

如何将 PostgreSQL 查询输出导出到 csv 文件

Android 的 JDBC 与 Web 服务

PL/pgSQL 执行与执行

Ruby 中 DateTime 的毫秒分辨率