doue9730 2016-04-08 14:37 采纳率: 100%
浏览 3508
已采纳

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

我试图像这样删除当前连接到的数据库,但我得到了以下错误:

pq: cannot drop the currently open database

要关闭连接是不是就必须要删除数据库?我不太理解,因为我认为我无法使用dbConn.Exec执行我的DROPDATABASE语句。

dbConn *sql.DB

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

  return dbConn.Close()
}

我想我可以连接到其他数据库,然后在那个连接上执行它,但我不确定这是否有效,而且如果这样做就必须连接到一个新的数据库,这看起来更麻烦了。有什么想法吗?谢谢。

  • 写回答

1条回答 默认 最新

  • dongxi1879 2016-04-08 15:04
    关注

    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:

    If PostgreSQL < 9.2

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

    Else

    SELECT pg_terminate_backend(pid) 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站