如何关闭 PostgreSQL 数据库上的空闲连接

How to close idle connection on PostgreSQL database

我一直在使用 python3 和 psycopg2 访问 postgreSQL 数据库。

我遇到了一个暗示我有打开的连接的错误。当我 运行 SELECT * FROM pg_stat_activity 我的用户名下出现了一堆连接。它们的状态都是 'idle',其中许多显示 "query" 值,而我从来没有 运行(例如:select 1show search_path)。

我看过 this 如何自动关闭它们。而且,我还读到使用 pg_terminate_backend 是危险的,会导致数据库重新启动。如何使用 python3 或 SQL 自然地关闭这些连接?它是公司生产数据库,因此无法重新启动它或成为管理员。如果我必须是管理员才能解决此问题,请告诉我。

您可以使用 pg_terminate_backend(pid int). 安全地终止您自己的空闲后端进程。如果您尝试终止您无权访问的进程,您将收到一条错误消息,并且不会发生任何特殊情况。不要尝试终止活动进程。

Per the documentation:

pg_terminate_backend(pid int)

Terminate a backend. This is also allowed if the calling role is a member of the role whose backend is being terminated or the calling role has been granted pg_signal_backend, however only superusers can terminate superuser backends.