RPostgreSQL无法关闭连接

时间:2015-10-13 09:24:07

标签: r rpostgresql

我有一个使用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来避免必须关闭连接。

有什么想法吗?

2 个答案:

答案 0 :(得分:14)

像这样构建你的代码:

MAX(trans_id)  Bank_state  forwarded_to
           71          16             2      

使用function() { con <- dbConnect("PostgreSQL") # + other params on.exit(dbDisconnect(con)) dbGetQuery("SELECT * FROM wherever") # or whatever you want to do } ,无论是否发生错误,都保证关闭连接。

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

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

on.exit

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

答案 1 :(得分:4)

如果你跑了con <- dbConnect("PostgreSQL") 不止一次,你有两个开放的连接,但con被覆盖,现在只引用第二个。快速解决:关闭所有打开的PostgreSQL连接,无论其名称如何:
lapply(dbListConnections(drv = dbDriver("PostgreSQL")), function(x) {dbDisconnect(conn = x)})
这通过检查驱动程序dbDriver(“PostgreSQL”)的所有打开连接来运行列表中的函数dbDisconnect()。

相关问题