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

当前回答

在PG管理中,您可以断开您的服务器(右键单击服务器)&所有会话将在重新启动时断开

其他回答

OSX, Postgres 9.2(已安装自制程序)

$ launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
$ pg_ctl restart -D /usr/local/var/postgres
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

如果你的datadir在其他地方,你可以通过检查ps aux | grep postgres的输出来找到它

只是想指出,如果一些其他后台进程正在使用数据库,哈里斯的答案可能无法工作,在我的情况下,它是延迟的工作,我做到了:

script/delayed_job stop

只有这样我才能删除/重置数据库。

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

案例: 查询执行失败:

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

这似乎适用于PostgreSQL 9.1:

#{Rails.root}/lib/tasks/databases.rake
# monkey patch ActiveRecord to avoid There are n other session(s) using the database.
def drop_database(config)
  case config['adapter']
  when /mysql/
    ActiveRecord::Base.establish_connection(config)
    ActiveRecord::Base.connection.drop_database config['database']
  when /sqlite/
    require 'pathname'
    path = Pathname.new(config['database'])
    file = path.absolute? ? path.to_s : File.join(Rails.root, path)

    FileUtils.rm(file)
  when /postgresql/
    ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
    ActiveRecord::Base.connection.select_all("select * from pg_stat_activity order by procpid;").each do |x|
      if config['database'] == x['datname'] && x['current_query'] =~ /<IDLE>/
        ActiveRecord::Base.connection.execute("select pg_terminate_backend(#{x['procpid']})")
      end
    end
    ActiveRecord::Base.connection.drop_database config['database']
  end
end

从这里和这里的胃肠道谱上提取的。

下面是一个修改后的版本,适用于PostgreSQL 9.1和9.2。