如何杀死我所有的postgresql连接?

我试着耙db:下降,但我得到:

ERROR:  database "database_name" is being accessed by other users
DETAIL:  There are 1 other session(s) using the database.

我尝试过关闭我从ps -ef | grep postgres中看到的进程,但这也不起作用:

kill: kill 2358 failed: operation not permitted

当前回答

如果你需要断开一个特定用户的会话,这有助于我:

检查当前所有连接:

select * from pg_stat_activity; 

授予你的用户一个角色(不重要):

set role "db_admin";

杀死届:

select pg_terminate_backend(pid)
from pg_stat_activity
where usename = '*** USER NAME TO DISCONNECT ***';

其他回答

可以使用pg_terminate_backend()终止连接。你必须是超级用户才能使用这个功能。这在所有操作系统上都是一样的。

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

在执行这个查询之前,你必须撤销CONNECT权限以避免新的连接:

REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;

如果你正在使用Postgres 8.4-9.1,请使用procpid而不是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'
    ;

我使用下面的rake任务来覆盖Rails drop_database方法。

lib / database.rake

require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLAdapter < AbstractAdapter
      def drop_database(name)
        raise "Nah, I won't drop the production database" if Rails.env.production?
        execute <<-SQL
          UPDATE pg_catalog.pg_database
          SET datallowconn=false WHERE datname='#{name}'
        SQL

        execute <<-SQL
          SELECT pg_terminate_backend(pg_stat_activity.pid)
          FROM pg_stat_activity
          WHERE pg_stat_activity.datname = '#{name}';
        SQL
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
      end
    end
  end
end

编辑:这是Postgresql 9.2+

打开PGadmin查看是否有任何查询页面打开,关闭所有查询页面,断开PostgresSQL服务器连接,重新连接,尝试删除/删除选项。这对我很有帮助。

案例: 查询执行失败:

DROP TABLE dbo.t_tabelname

解决方案: a.显示查询状态活动如下:

SELECT * FROM pg_stat_activity  ;

b.查找“查询”列包含的行:

'DROP TABLE dbo.t_tabelname'

c.在同一行中,获取“PID”列的值

example : 16409

d.执行以下脚本:

SELECT 
    pg_terminate_backend(25263) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    25263 <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;
SELECT 
pg_terminate_backend(pid) 
FROM 
pg_stat_activity 
WHERE
pid <> pg_backend_pid()
-- no need to kill connections to other databases
AND datname = current_database();
-- use current_database by opening right query tool