如何杀死我所有的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

当前回答

案例: 查询执行失败:

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

其他回答

我使用下面的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+

关于运行进程的所有信息:

SELECT *, pg_terminate_backend(pid)
FROM pg_stat_activity 
WHERE pid <> pg_backend_pid()
AND datname = 'my_database_name';

也许只是重启postgres => sudo服务postgresql重启

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

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