我有一个闪亮的应用程序,使用它连接到数据库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
never dbSendQuery
以避免必须关闭连接。
有任何想法吗?
像这样构造你的代码:
function()
{
con <- dbConnect("PostgreSQL") # + other params
on.exit(dbDisconnect(con))
dbGetQuery("SELECT * FROM wherever") # or whatever you want to do
}
通过使用on.exit
,无论是否发生错误,连接都保证关闭。
也可以看看我应该如何以及何时使用 on.exit? https://stackoverflow.com/q/28300713/134830
如果需要,您可以使用以下命令卸载驱动程序:
on.exit(dbUnloadDriver(drv), add = TRUE)
我怀疑这可能会提供更差的性能,因为每次连接到数据库时都会卸载并重新加载驱动程序。如果您担心这一点,请在您的使用条件下进行测试。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)