RODBC Multiple Inputs from Shiny

北战南征 提交于 2019-12-12 01:58:49

问题


I have a Shiny app that has a checkbox group input. The user can select multiple inputs. I also have an ODBC connection linked to a database. The process would be that when a user selects items from the check box group, that user input would be part of a string in the sql query to filter the data.

UI.R (partial to show example)

checkboxGroupInput('Type', 'Type', c(
                          "AX"="AX",
                          "AY"="AY",
                          "AZ"="AZ",
                          "BGB"="BGB",
                          "BT"="BT",
                          "BX"="BX",
                          "BXT"="BXT",
                          "C"="C",
                          "CNT"="CNT")),

The column in the table where the "Type" information is in is called COMPONENT, so my sql query using RODBC is

data <- odbcConnect("database", uid="username", pwd="password")
query <- (SELECT ID, NAME, TYPE FROM COMPONENT WHERE TYPE LIKE Input$Type)
df <- odbcQuery(data, query)

The query line would not work, but I have no idea how to take multiple inputs and place them properly in the query. Also, there is an added level of complexity that I am not sure how to handle. The data in the database is alpha numeric, so instead of AX, it might be listed as AX14 or AX 71. Also, because there are some one letter types, using a wildcard seems a little difficult.


回答1:


To answer your initial question regarding "multiple inputs in the query", I use concatenation to achieve this.

Using paste0(), I write something as follows:

type = "AX14"
myQuery <- paste0("Select variable1, variable2 from my_table where type like ",type)
myQuery
[1] "Select variable1, variable2 from my_table where type like AX14"

You can add little things like single quotes or wildcard operators as follows:

myQuery <- paste0("Select variable1, variable2 from my_table where type like '%",type,"%'")
myQuery
[1] "Select variable1, variable2 from my_table where type like '%AX14%'"

Then proceed with actually running the query:

df <- odbcQuery(data, myQuery)



来源:https://stackoverflow.com/questions/25187858/rodbc-multiple-inputs-from-shiny

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