2015-10-13 101 views
2

我有一个闪亮的应用程序,使用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避免关闭连接。

任何想法?

回答

8

结构化你这样的代码:

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) 

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

+0

我必须卸载驱动程序吗? – David

+0

我只是不喜欢这样写道: 库(RODBC) DBConnection的< - odbcDriverConnect(“驱动程序= ODBC SQL Server的驱动程序11;服务器= RSHUELL00193 \\ SQLEXPRESS;数据库= TESTDB; UID =; PWD =; trusted_connection =是)“) initdata < - sqlQuery(dbconnection,paste(”select * from MyTable;“)) odbcClose(channel) 我完全没有问题。 – ryguy7272