gpt4 book ai didi

mysql - 将多个选择从 selectizeInput 传递到 MySQL 查询

转载 作者:行者123 更新时间:2023-11-29 10:04:58 25 4
gpt4 key购买 nike

我正在尝试将 selectizeInput 的多个值传递给 MySQL 查询。

问题是在 Shiny 的应用程序中这种操作的正确语法是什么?

我尝试过并且正在使用一个值

  library(shiny)
library(DBI)
library(RMySQL)

server <- shinyServer(function(input, output, session) {
con <- dbConnect(MySQL(), user='user', port = 3306,
password='pwd', dbname='db', host='host' )

on.exit(dbDisconnect(con), add = TRUE)

output$textview <- renderUI({

con <- dbConnect(MySQL(), user='user', port = 3306, password='pwd',
dbname='db', host='host' )

on.exit(dbDisconnect(con), add = TRUE)


text <- reactive({
dbGetQuery(con, statement =
paste0(" SELECT author, title, publicationDate, FROM publications
WHERE publications.year LIKE %'",input$year,"'% ")
)
})

text <-text()
HTML(text)

})




session$onSessionEnded(function() { dbDisconnect(con) })
})


ui_panel <-
tabPanel("Multi-Select Input Test",
sidebarLayout(
sidebarPanel(


selectizeInput('year', 'Select Year of publication:', choices =
publications.year, multiple = TRUE options = list(maxOptions = 5)
),

br(),
submitButton("Update Text View"),
br()
),
mainPanel(
tabsetPanel(tabPanel("Text",htmlOutput("textview"))

)
)
))


ui <- shinyUI(navbarPage(" ",ui_panel))

runApp(list(ui=ui,server=server))

MySQL 命令中允许我从 selectizeInput (input$year) 传递多个值的正确语法是什么?我尝试使用 IN 而不是 LIKE,如下所示,但它不起作用

    text <- reactive({
dbGetQuery(con, statement =
paste0(" SELECT author, title, publicationDate, FROM
publications WHERE publications.year IN %'",input$year,"'% ")
)
})

最佳答案

您需要构造一个与此类似的 SQL:

SELECT * FROM publications WHERE year IN (2016, 2017)

这应该生成:

text <- reactive({
year_selected <- paste(input$year, collapse = ',')
sql = paste("SELECT * FROM publications WHERE year IN (",year_selected,")")
dbGetQuery(con, statement = sql)
})

一个最小的 Shiny 应用程序:

library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectizeInput('year', 'Select Year of publication:',
choices = c(2017L, 2018L),
multiple = TRUE,
options = list(maxOptions = 5)
)
),
mainPanel(
verbatimTextOutput('text')
)
)
)

server <- function(input, output) {
output$text <- renderText({
library(glue)
year_selected <- paste(input$year, collapse = ',')
glue("SELECT * FROM publications WHERE year IN ({year_selected})")
})
}

shinyApp(ui = ui, server = server)

关于mysql - 将多个选择从 selectizeInput 传递到 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52090142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com