Creating a SQL query using selectinput in R shiny

半世苍凉 提交于 2019-12-08 08:53:57

问题


I am trying to create a dynamic query using select input.

Something like

Select * from basket where fruits in("apple","banana","cherry")

I have a table called fruit_list which populates my selectinput box.

selectInput("fruit_list", label = h5("Select fruit"), multiple = T, choices = (dbGetQuery(conn, "SELECT fruit from fruit_list');")))

So far, when i renderprint my selection I get "apple" "banana" "cherry" I need a comma between the elements to get "apple","banana","cherry" When i choose a single element from the multiselect box "apple"

Select * from basket where fruits in("apple")

my application runs perfectly. However, when i select more than one element "apple" "banana" I get an error: Expecting a single string value: [type=character; extent=2].

I apologize for not being as explicit in the beginning


回答1:


Suppose ans is a non-empty subset of c("a", "b", "c", "d") . For example,

ans <- c("b", "d")
sprintf("select * from table where item in (%s)", toString(shQuote(ans, "csh")))

giving:

[1] "select * from table where item in ('b', 'd')"

If you are using R 3.6 or later you can optionally replace the shQuote(ans, "csh") with sQuote(ans, FALSE) .

If a, b, c, d in the question were supposed to represent numbers then we don't need the quotes so we can replace toString(...) with just toString(ans) .

No packages are used.




回答2:


selectInput takes in user input as a character vector, glue should be more easier to use when your query is more complex.

library(glue)
# user_input <- input$selectInput # e.g. c("a","b","c","d")
user_input <- c("a","b","c","d")
sql_where <- paste0(user_input,collapse = ", ")
glue("select * from table where item in ({sql_where})")

It translates into:

select * from table where item in (a, b, c, d)


来源:https://stackoverflow.com/questions/58066371/creating-a-sql-query-using-selectinput-in-r-shiny

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!