This question is admittedly similar to this question but the answer provided is not sufficient for my example.
I am creating a Shiny App that connects to a database. The user can provide some inputs and some 'canned' queries will run. Now, I would like to make certain the connection to the database is closed on exit from the app. I could use a button and the stopApp
function but this assumes users will be good and always click said button. Users are likely to sometimes close the window leaving the database connection open so I would like to find a way to explicitly close the connection when the user closes the app window.
I suppose one solution would be to instantiate a new connection and close at the end of each query but that seems inefficient.
Here is some working code to demonstrate the problem. If I run this App from Rstudio and then close the window, I still have an existing connection as per dbListConnections(PostgreSQL())
. Appending dbDisconnect(con)
to the end of the file does not help.
library(shiny)
library(RPostgreSQL)
server <- shinyServer(function(input, output){
# Read in the dataset
connectDB <- eventReactive(input$connectDB, {
if(input$drv != "postgresql"){
stop("Only 'postgresql' implemented currently")
}else{
drv <- dbDriver("PostgreSQL")
port = 5432
}
con <- dbConnect(drv, user = input$user, password = input$passwd,
port = port, host = input$server, dbname=input$db_name)
con
})
output$test <- renderText({
con <- connectDB()
"connection success"
})
})
ui <- shinyUI(
fluidPage(
titlePanel("Test Connection"),
sidebarLayout(
sidebarPanel(
textInput("drv", "Database Driver", value="postgresql"),
textInput("user", "User ID"),
textInput("server", "Server", value="server"),
textInput("db_name", "Database Name", value="dbName"),
passwordInput("passwd", "Password"),
actionButton("connectDB", "Connect to DB")
),
mainPanel(
textOutput("test")
)
)
)
)
shinyApp(ui=ui, server=server)