Postgresql-新建\删除数据库-异常 DETAIL: There are 3 other sessions using the database.

场景描述:

异常1: 

postgres@f644d67d23c6:~$ psql
psql: FATAL:  database "postgres" does not exist

解决方式:Navicat连接数据库,执行:

CREATE USER postgres SUPERUSER;

异常2: 执行如下创建命令的时候报错:

template1=# CREATE DATABASE customs_data OWNER admin;
ERROR:  source database "template1" is being accessed by other users

DETAIL:  There are 3 other sessions using the database.

处理方式:

    登录数据库所在服务器,命令行连接数据库:

        psql template1

    确认谁在连接使用 template1: 

        select * from pg_stat_activity where DATNAME = 'template1';

    将相应连接pid进程关闭:

        select pg_terminate_backend(1446); 

template1=# select * from pg_stat_activity where DATNAME = 'template1';
 datid | datname  | pid  | usesysid | usename | application_name | client_addr | client_hostname | client_port | backend_start| xact_start | query_start | state_change | waiting | state  | backend_xid | backend_xmin | query                                                                          
-------+----------+------+----------+---------+------------------+---------- --+-----------------+-------------+---------------------------+----------------------------+---------+--------+-------------+--------------+-------+
     1 |template1 | 1693 |    17302 |postgres | psql             |             |                 |          -1 | 2021-01-25 09:23:03.940082+00 | 2021-01-25 09:23:39.727448+00 | 
2021-01-25 09:23:39.727448+00 | 2021-01-25 09:23:39.727452+00 | f       | active |             |      7713874 | select * from pg_stat_activity where DATNAME = 'template1';
     1 | template1 | 1446 |       10 | admin    |                  | 222.209.33.183 |                 |       57668 | 2021-01-25 08:49:10.710847+00 |                               | 
2021-01-25 08:49:22.730209+00 | 2021-01-25 08:49:22.755726+00 | f       | idle   |             |              | SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolc
atupdate, rolcanlogin, rolconnlimit, rolvaliduntil, rolconfig, oid FROM pg_roles 
(2 rows)

template1=# SELECT pg_terminate_backend(1446);                           
 pg_terminate_backend 
----------------------
 t
(1 row)

然后再次执行创建数据库命令&授权命令:

template1=# CREATE DATABASE customs_data OWNER admin;                                                                                             
CREATE DATABASE

template1=# GRANT ALL PRIVILEGES ON DATABASE customs_data TO admin;
GRANT

 注意:另一种情况drop删除数据库时,也可能出现出现该异常,但是处理的时候,一定要谨慎,因为涉及删除drop数据库。

postgres=# drop database hnair;                                                        
ERROR:  database "hnair" is being accessed by other users
DETAIL:  There is 1 other session using the database.

 

posted @ 2022-07-27 10:35  hello-Jesson  阅读(646)  评论(0编辑  收藏  举报