You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用psycopg2操作PostgreSQL时连接长期处于idle状态引发连接耗尽的问题求助

psycopg2操作PostgreSQL时连接长期处于idle状态引发连接耗尽的问题求助

我最近在使用psycopg2向PostgreSQL数据库插入数据时遇到了连接残留的问题,想请教大家怎么解决:

最开始我用下面的代码插入数据,每次运行后,pg_stat_activity里都会留下一个状态为idle的数据库连接,不会自动释放:

column_names = ", ".join(columns)

query = f"INSERT INTO {table_name} ({column_names}) VALUES %s"
values = [tuple(record.values()) for record in records]

with psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port, application_name=app_name) as conn:
    with conn.cursor() as c:
        psycopg2.extras.execute_values(cur=c, sql=query, argslist=values, page_size=batch_size)

UPDATE: 后来根据Adrian的建议,我把代码改成了下面这样:

conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port, application_name=app_name)
with conn:
    with conn.cursor() as c:
        psycopg2.extras.execute_values(cur=c, sql=query, argslist=values, page_size=self._batch_size)
        conn.commit()
conn.close()
del conn

但问题还是没解决,当我多次运行这段代码后,突然抛出了连接耗尽的错误:

E       psycopg2.OperationalError: connection to server at "localhost" (::1), port 5446 failed: Connection refused (0x0000274D/10061)
E           Is the server running on that host and accepting TCP/IP connections?
E       connection to server at "localhost" (127.0.0.1), port 5446 failed: FATAL:  remaining connection slots are reserved for roles with the SUPERUSER attribute

我现在有点疑惑,会不会是因为我是通过VSCode的SSH端口转发连接到Azure云数据库导致的这个问题?而且我用DBeaver客户端连接的时候,也遇到了同样的连接残留情况。

备注:内容来源于stack exchange,提问作者Joysn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 11:54:35