Kill a postgresql session/connection

前端 未结 20 1950
暖寄归人
暖寄归人 2020-11-28 00:11

How can I kill all my postgresql connections?

I\'m trying a rake db:drop but I get:

ERROR:  database \"database_name\" is being accessed         


        
20条回答
  •  没有蜡笔的小新
    2020-11-28 00:28

    You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function. This works on all operating systems the same.

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

    Before executing this query, you have to REVOKE the CONNECT privileges to avoid new connections:

    REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;
    

    If you're using Postgres 8.4-9.1 use procpid instead of pid

    SELECT 
        pg_terminate_backend(procpid) 
    FROM 
        pg_stat_activity 
    WHERE 
        -- don't kill my own connection!
        procpid <> pg_backend_pid()
        -- don't kill the connections to other databases
        AND datname = 'database_name'
        ;
    

提交回复
热议问题