0

My requirement is to build a Shiny application that connects once and only once to the database, when the application is launched. If the database times out the connection, that is fine. Similarly, when a user closes the window, the database connection should be closed. This Shiny application has a Submit button that will do a CRUD operation depending on other form inputs.

In what section of a Shiny application can I handle application launch and termination so that I can connect and close database connection correspondingly?

cogitoergosum
  • 2,309
  • 4
  • 38
  • 62

1 Answers1

1

You can connect to your database at the application launch in global.R. This will make available the DB connection to all the application sessions. But maybe you will be more interested to create the connection with the DB each time a new session starts, for that you can create the connection inside your server function in server.R. To close the database you can use session$onSessionEnded. See the sample code below.

server <- function(input, output, session) {
  # code to connect to DB

  # ... 

  # code to disconnect the DB
  session$onSessionEnded(function() {
    # this funtion will be execute when session ends
    # like when the user closes the window
    # disconnect DB...

  })
}
Geovany
  • 5,389
  • 21
  • 37