我想编写一个带有r的任意sql查询

3wabscal  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(360)

在这段代码中,slectinput的多个选定列是从sql获取的。

用户界面

shinyUI(
  fluidPage(
    selectInput("select","select", 
                choices = c("ID","Name","CountryCode","District","Population"),
                multiple = TRUE),
    textOutput("sql_"),
    tableOutput("table")
  )
)

服务器.r

shinyServer(function(input, output) {

    output$table <- renderTable({
      sql <- paste('SELECT ', paste0("\"", input$select, "\"", collapse = ","),' FROM City;',seq = "")
      output$sql_ <- renderText(sql)
      query <- sqlInterpolate(pool, sql)
      dbGetQuery(pool, query)
    })
})

全局.r

library(shiny)
library(DBI)
library(pool)

pool <- dbPool(
  drv = RMySQL::MySQL(),
  dbname = "shinydemo",
  host = "shiny-demo.csa7qlmguqrf.us-east-1.rds.amazonaws.com",
  username = "guest",
  password = "guest"
)

我认为sql语法是正确的。但我不能把它放在table上。不知为什么我得到了列名。有解决办法吗?

dgtucam1

dgtucam11#

这是因为你把它放在引号里,试试这个:

q <- eventReactive(input$select,{
        query <- 'SELECT VARIABLES FROM City'
        query <- gsub("VARIABLES",paste0(input$select,collapse = ","),query) 
        query
    })

    output$sql_ <- renderText({
        q()
    })

    output$table <- renderTable({
        query <- sqlInterpolate(pool, q())
        dbGetQuery(pool, query)
    })

相关问题