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

当前回答

没有必要放弃。只需删除并重新创建公共模式。在大多数情况下,这有完全相同的效果。

namespace :db do

desc 'Clear the database'
task :clear_db => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.tables.each do |table|
    next if table == 'schema_migrations'
    ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
  end
end

desc 'Delete all tables (but not the database)'
task :drop_schema => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.execute("DROP SCHEMA public CASCADE")
  ActiveRecord::Base.connection.execute("CREATE SCHEMA public")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO postgres")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO public")
  ActiveRecord::Base.connection.execute("COMMENT ON SCHEMA public IS 'standard public schema'")
end

desc 'Recreate the database and seed'
task :redo_db => :environment do |t,args|
  # Executes the dependencies, but only once
  Rake::Task["db:drop_schema"].invoke
  Rake::Task["db:migrate"].invoke
  Rake::Task["db:migrate:status"].invoke 
  Rake::Task["db:structure:dump"].invoke
  Rake::Task["db:seed"].invoke
end

end

其他回答

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

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的输出来找到它

MacOS,如果postgresql安装了brew:

brew services restart postgresql

UBUNTU,

首先用这个检查(在后台运行的kill服务器)

sudo kill -9 $(lsof -i :3000 -t)

如果你没有找到pid,那么你只需要重新启动 Postgresql服务的命令如下所示:

sudo service postgresql restart

答案隐藏在上面的一条评论中:brew服务重新启动postgresql

我有这个问题,问题是Navicat连接到我本地的Postgres数据库。一旦我断开Navicat,问题就消失了。

编辑:

此外,作为最后的手段,你可以备份你的数据,然后运行这个命令:

sudo kill -15 `ps -u postgres -o pid`

... 这将杀死postgres用户正在访问的所有内容。避免在生产机器上这样做,但在开发环境中应该不会有问题。在尝试重启PostgreSQL之前,确保每个postgres进程都已经真正终止是至关重要的。

编辑2:

由于这个unix。SE post我从击杀-9改为击杀-15。