在pgsql中使用pg_terminate_backend()函数来关闭数据库.
官方文档中:
pg_terminate_backend(pidint),Terminate a backend. You can execute this against another backend that has exactly the same role as the user calling the function. In all other cases,you must be a superuser.return type:boolean
pg_terminate_backend()函数需要超级用户才能够执行,此外它还需要接收一个pid的参数,这个参数来自pg_stat_activity表
方法:
先找到指定数据库的pid:
SELECT datname,pid FROM pg_stat_activity;
SELECT pg_terminate_backend(11480);
其实可以一步完成:
SELECT CAST(pg_terminate_backend(pid) AS VARCHAR(10)) FROM pg_stat_activity WHERE datname='db3';
SELECT CAST(pg_terminate_backend(pid) AS VARCHAR(10)) FROM pg_stat_activity WHERE usename='sec03';
使用pg_terminate_backend()关闭连接但是它会等待当前所有的查询结束才会断开,如果想立即断开所有连接我们可以使用pg_cancel_backend()断开连接,并且不再允许连接:
原文链接:https://www.f2er.com/postgresql/195330.htmlSELECT CAST(pg_cancel_backend(pid) AS VARCHAR(10)) FROM pg_stat_activity WHERE datname='db3';