0
votes

While trying to pass an user entered input (empId) from Shiny UI into a sql query on shiny server.r not sure how to debug this error.

 Error in as.vector(x, "character") : 
 cannot coerce type 'closure' to vector of type 'character'

UI.r

library(shiny)

shinyUI(fluidPage(
titlePanel("Employee Table (AdventureWorks)"),
sidebarLayout(
sidebarPanel((""),
             textInput("idnumb", "Employee ID number",""),
             submitButton("Ok")),
             mainPanel(tableOutput("emptitle")))))

Server.r

 shinyServer(function(input, output) {
 library(RODBC)
 library(sqldf)
 a1 = reactive({ (input$idnumb) })
 acc_con1 = odbcConnect("AdvWrk", uid="... ", pwd="... ")
 sql1 = sqlQuery(acc_con1, paste0('select Title from dbo.Employee where EmployeeID=',a1))
 output$emptitle = renderTable(print(sql1))
 })

To test if my query works , I tired this with the actual EmployeeID in the sql like this below

  .
  .
  sql1 = sqlQuery(acc_con1, paste0('select Title from dbo.Employee where EmployeeID = 8'))
  .
  .

I get a normal ouput,

  Title
  Production Technician - WC10 

When I try to make this reactive to user input i see Error in as.vector(x, "character") : cannot coerce type 'closure' to vector of type 'character...error...Need help.

2

2 Answers

1
votes

Main problem in your code is that you give reactive function "a1" as argument to sqlQuery function. sqlQuery expects you to give character as argument.

In this case where you want to monitor any changes in input. You could use observe function. I also added error checking line to make sure that you actually have some value in a input$idnumb

shinyServer(function(input, output) {
         library(RODBC)
         library(sqldf)
            observe({
            if(input$idnumb ==NULL)
               return(NULL)
            acc_con1 = odbcConnect("AdvWrk", uid="... ", pwd="... ")
            sql1 = sqlQuery(acc_con1, paste0('select Title from dbo.Employee where EmployeeID=',input$idnumb))
            )}
        output$emptitle = renderTable(print(sql1))
 )}
0
votes

I also agree with @Mikael Jumppanen that

Main problem in your code is that you give reactive function "a1" as argument to sqlQuery function. sqlQuery expects you to give character as argument.

However the solution is much simpler: you should simply call a1() instead of a1 since you have defined it as a reactive function.

 sql1 = sqlQuery(acc_con1, paste0('select Title from dbo.Employee where EmployeeID=',a1()))

Can you please try it?