RPostgreSQL 无法关闭连接

RPostgreSQL Cannot Close Connections

我有一个闪亮的应用程序,它使用 RPostgreSQL 连接到数据库。在应用程序结束时,连接已关闭,应该卸载驱动程序,但我收到错误消息,警告我连接未关闭。

代码看起来像这样:

 # in the app.R file, but not in the server function:
 drv <- dbDriver("PostgreSQL")
 con <- dbConnect(drv, dbname = "database1",
                host = "localhost", port = 5432,
                user = "user", password = "pw")

# in the server function:
foo <- dbGetQuery(con, "SELECT * from table1")

# at the end of the server function to disconnect when the app is closed:
session$onSessionEnded(function(){
    dbDisconnect(con)
    dbUnloadDriver(drv)
})

但是,我收到错误消息:Error in postgresqlCloseDriver(drv, ...): RS-DBI driver: (There are opened connections -- close them first) 这是通过命令 dbUnloadDriver(drv) 显示的。

当我使用 dbListConnections() 手动查找打开的连接时,我得到一个列表,其中包含最多 16 个打开的数据库连接。请注意,我只使用 dbGetQuery 而从不使用 dbSendQuery 以避免必须关闭连接。

有什么想法吗?

像这样构建代码:

function()
{
  con <- dbConnect("PostgreSQL") # + other params
  on.exit(dbDisconnect(con))

  dbGetQuery("SELECT * FROM wherever") # or whatever you want to do
}

通过使用on.exit,保证关闭连接,无论是否发生错误。

另见 How and when should I use on.exit?


如果需要,可以使用以下方法卸载驱动程序:

on.exit(dbUnloadDriver(drv), add = TRUE)

我怀疑这可能会提供更差的性能,因为每次连接到数据库时都会卸载和重新加载驱动程序。如果担心这个,请在​​您的使用条件下进行测试。

如果你运行con <- dbConnect("PostgreSQL") 不止一次,您有两个打开的连接,但是 con 被覆盖,现在只引用第二个。快速补救措施:关闭所有打开的 PostgreSQL 连接,无论它们的名称如何:
lapply(dbListConnections(drv = dbDriver("PostgreSQL")), function(x) {dbDisconnect(conn = x)})
这将在通过检查与驱动程序 dbDriver("PostgreSQL").

的所有打开连接而获得的列表上运行函数 dbDisconnect()