Creating a SQL query using selectinput in R shiny

你。 提交于 2019-12-08 18:14:25

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.

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