r—将textinput值传递给mysql查询的语法

o2gm4chl  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(289)

我正在尝试将textinput的值传递到mysql查询中。
第一个问题是,当使用mysql作为驱动程序时,like操作符与textinput组合的正确语法是什么?我应该把%%放在查询语句的哪里?
其次是如何最好地捕获textinput的React性,以便能够将其传递给查询并创建一个表?

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$tableview <- renderTable({

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

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

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

                    table()

              })

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

ui_panel <- 
        tabPanel("Text Input Test",
          sidebarLayout(
            sidebarPanel( 

             textInput("textSearch", " Search for keyword", ''),

                       br(),
                       submitButton("Update Table View"),
                       br()
           ),
           mainPanel(
           tabsetPanel(tabPanel("Table",tableOutput("tableview"))

           )
         )
    ))

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

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

类似的问题:如何在ui.r中读取textinput,在global.r中处理具有此值的查询,并在server.r中使用shinny显示,shinny处理输出,并处理在本例中没有的全局文件。
欢迎有任何见解。

c6ubokkw

c6ubokkw1#

当前代码应构造以下sql:

SELECT ... FROM publications WHERE publications.abstract LIKE %'test'%

问题是: % 应该在里面 '' .
更新的行:

paste0("SELECT author, title, publicationDate,  FROM publications WHERE publications.abstract LIKE '%",input$textSearch,"%' ")

然后它应该构造以下sql:

SELECT author, title, publicationDate, FROM publications WHERE publications.abstract LIKE '%test%'

对于测试,我建议使用 renderText() 以及 verbatimTextOutput() 看看结果。
您还可以考虑使用glue包来安全地构造sql查询。
对于第二个问题,文章中的“操作按钮”可能会有用。

相关问题