I am making an interactive Shiny app that searches a MySQL database on my computer. I can access the database and properly execute queries in R scripts and static Shiny apps, but I run into trouble when trying to execute queries only when a user clicks on an action button.
The problems occur when I wrap my queries in Shiny's event triggered functions, like observeEvent()
. For example, the following code runs and retrieves the right set of data:
shinyServer(function(input, output, session){
con <- dbConnect(RMySQL::MySQL(), dbname = "testdb", user='testuser', password = "testpassword")
tableList <- dbListTables(con)
output$out <- renderPrint(tableList) #this always prints
df <- data.frame()
#observeEvent(input$button, {
quer <- paste("select id, dept, course_code from main_course_info
where dept in (select id from dept_relations
where deptName = 'CMPE')")
df <- data.frame(dbGetQuery(con, quer))
output$table <- renderTable({df})
#})
dbDisconnect(con)
})#shinyServer
With the observeEvent
function commented out, the query runs perfectly and the retrieved table is displayed. But when I try to hold the query off until input$button changes, i.e the button gets pressed, i get the following error upon pressing the button:
Warning in run(timeoutMs) :
Unhandled error in observer: internal error in RS_DBI_getConnection: corrupt connection handle
observeEvent(input$button)
I need this button functionality to work, because my goal is to have the specifics of the query decided by user inputs, which would be brought together and executed once the user has made their selections and hit the action button. However I cannot even get a predefined query to run with observeEvent
, which is integral to the design of my app.
Note that the first output, a renderPrint
of the list of tables in the database, always prints regardless of the success or failure of the button. This means that the connection is working at least until it gets sent to observeEvent
's handler argument.