ERROR: database "testdb" is being accessed by other users

from:https://www.cnblogs.com/hellojesson/p/10037315.html

执行DROP DATABASE testdb;的时候提示:

ERROR: database "testdb" is being accessed by other users
DETAIL: There are 3 other sessions using the database.

注:PostgreSQL在有进程连接到数据库时,对应的数据库是不运行被删除的。

解决办法:断开连接到这个数据库上的所有链接,再删除数据库。在PostgreSQL 9.2 及以上版本,执行下面的语句:

SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname='testdb' AND pid <> pg_backend_pid();

执行上面的语句之后,再执行DROP即可。

说明:

pg_terminate_backend:用来终止与数据库的连接的进程id的函数。

pg_stat_activity:是一个系统表,用于存储服务进程的属性和状态。

pg_backend_pid():是一个系统函数,获取附加到当前会话的服务器进程的ID

Copyright © 2021 Primzahl. All rights reserved.

原文地址:https://www.cnblogs.com/Primzahl/p/13523061.html