2015-10-13 100 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