PostgreSQL 删除数据库时报错 ERROR: database "test" is being accessed by other users

PostgreSQL About 696 words

错误信息

查询出错 (7): ERROR: database "test" is being accessed by other users
DETAIL: There are 10 other sessions using the database.

问题原因

其他进程正在连接此数据库,需要kill掉正在使用此数据库的连接。

解决方法

方法一(推荐)

强制删除。

适用于PostgreSQL 13及以上。

备注:都到了删除数据库的地步了,强不强制已经不重要了。

DROP DATABASE test WITH (FORCE);

方法二

通过pg_terminate_backend结束除了当前进程外的其他进程,然后再执行DROP命令。

适用于PostgreSQL 12及以下。

test替换为需要删除的数据库名字。

步骤一:kill其他进程。

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 = 'test'
    ;

步骤二:删除数据库。

DROP DATABASE test;

参考文档

https://www.postgresql.org/docs/13/sql-dropdatabase.html

Views: 125 · Posted: 2024-03-14

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh