Postgres删除数据库错误:pq:不能删除当前打开的数据库 [英] Postgres drop database error: pq: cannot drop the currently open database

查看:4921
本文介绍了Postgres删除数据库错误:pq:不能删除当前打开的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图删除当前连接的数据库,但是我收到了这个错误消息:

  pq:无法删除当前打开的数据库

我不太了解我的预期删除数据库,如果我不得不关闭我的连接,因为那么我不认为我将能够使用dbConn.Exec执行我的DROP DATABASE语句?

 dbConn * sql.DB 

func stuff()错误{
_,err:= dbConn.Exec(fmt.Sprintf(`DROP DATABASE%s ;`dbName))
if err!= nil {
return err
}

return dbConn.Close()
}

我想我可以连接到不同的数据库,然后在该连接上执行它,但我甚至不确定是否这会起作用,并且为了删除不同的数据库而必须连接到新的数据库似乎很奇怪。有任何想法吗?感谢。

解决方案

因为您尝试执行 dropDb 命令数据库,你有开放的连接。



根据postgres文档:


您无法连接到您即将删除的数据库。


这很有道理,因为当您删除整个数据库时,所有引用该数据库的开放连接都变为无效,因此推荐的方法是连接到不同的数据库,并再次执行此命令。



如果您遇到某种情况,如果不同的客户端连接到数据库,并且确实想要删除数据库,则可以强制断开该特定数据库中的所有客户端。



例如,要将强制从数据库中断开所有客户端 mydb


$ b

SELECT pg_terminate_backend(procpid)FROM pg_stat_activity WHERE datname ='mydb';



注意:此命令需要超级用户权限。 b

然后,您可以连接到不同的数据库,然后再次运行 dropDb 命令。


I'm trying to drop the database I'm currently connected to like so, but I'm getting this error:

pq: cannot drop the currently open database

I don't really understand how I'm expected to drop the database if I have to close my connection, because then I don't think I will be able to use dbConn.Exec to execute my DROP DATABASE statement?

dbConn *sql.DB

func stuff() error {
  _, err := dbConn.Exec(fmt.Sprintf(`DROP DATABASE %s;`, dbName))
  if err != nil {
    return err
  }

  return dbConn.Close()
}

I guess I could connect to a different database and then execute it on that connection, but I'm not even sure if that'd work, and it seems really weird to have to connect to a new database just to drop a different database. Any ideas? Thanks.

解决方案

Because, you are trying to execute dropDb command on database, to which you have open connection.

According to postgres documentation:

You cannot be connected to the database you are about to remove. Instead, connect to template1 or any other database and run this command again.

This makes sense, because when you drop the entire database, all the open connection referencing to that database becomes invalid, So the recommended approach is to connect to different database, and execute this command again.

If you are facing a situation, where a different client is connected to the database, and you really want to drop the database, you can forcibly disconnect all the client from that particular database.

For example, to forcibly disconnect all clients from database mydb:

SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = 'mydb';

Note: This command requires superuser privileges.

Then, you can connect to different database, and run dropDb command again.

这篇关于Postgres删除数据库错误:pq:不能删除当前打开的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆