您可以使用pg_terminate_backend()终止连接。您必须是超级用户才能使用此功能。这在所有操作系统上均相同。
SELECT
pg_terminate_backend(pid)
FROM
pg_stat_activity
WHERE
-- don't kill my own connection!
pid <> pg_backend_pid()
-- don't kill the connections to other databases
AND datname = 'database_name'
;
在执行此查询之前,您必须撤销 CONNECT特权以避免建立新连接:
REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;
如果您使用的是Postgres 8.4-9.1,请使用procpid而不是pid
SELECT
pg_terminate_backend(procpid)
FROM
pg_stat_activity
WHERE
-- don't kill my own connection!
procpid <> pg_backend_pid()
-- don't kill the connections to other databases
AND datname = 'database_name'
;