Postgres drop database error: pq: cannot drop the currently open database

后端 未结 4 980
别那么骄傲
别那么骄傲 2021-02-05 01:21

I\'m trying to drop the database I\'m currently connected to like so, but I\'m getting this error:

pq: cannot drop the currently open database

4条回答
  •  既然无缘
    2021-02-05 02:05

    Because, you are trying to execute dropDb command on database, to which you have open connection.

    According to postgres documentation:

    You cannot be connected to the database you are about to remove. Instead, connect to template1 or any other database and run this command again.

    This makes sense, because when you drop the entire database, all the open connection referencing to that database becomes invalid, So the recommended approach is to connect to different database, and execute this command again.

    If you are facing a situation, where a different client is connected to the database, and you really want to drop the database, you can forcibly disconnect all the client from that particular database.

    For example, to forcibly disconnect all clients from database mydb:

    If PostgreSQL < 9.2

    SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = 'mydb';

    Else

    SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'mydb';

    Note: This command requires superuser privileges.

    Then, you can connect to different database, and run dropDb command again.

提交回复
热议问题