通过单击输入文本框,从R Shiny运行SQL查询

我创建了一个带有运行按钮的闪亮应用程序,用于运行sql查询以从mysql数据库检索数据。这样检索到的数据将作为R Shiny的输入

  library(DBI)
  library(bigrquery)
  library(readr)
  library(shiny)

以上步骤将导入库。

接下来,我们创建数据库连接参数

    project <- "A-dev"
    dataset <- "A_table"
    con <- dbConnect( bigrquery::bigquery(),project = project,dataset = 
    dataset)

在数据集中,是一组包含我们需要提取的参数的列。用于提取这些列值的查询如下

query2 <- "select C_name from A_table group by 
C_name"

上面的查询将创建一个值列表,用作R Shiny中的下拉输入选择

以下是该应用程序的结构。

闪亮的应用程序的UI如下创建。该布局包含一个用于运行查询的“运行”按钮,以及一组将返回查询结果的下拉菜单

   ui <- fluidPage(

   sidebarLayout(sidebarPanel(actionButton(inputId = "Button",label = "run 
  Query"),uiOutput(outputId = "List1")),mainPanel(dataTableOutput(outputId = "Table1")) ))

应用程序的服务器部分如下

     server <- function(input,output,session) {

      ##### Here the action button is connected
       my_data <- reactive({ 
       if(input$Button == 0)
       {return(0) }
       isolate({
       input$Button


    query2 <- "select C_name from A_table group by C_name"


      df <- query_exec(query2,useLegacySql = FALSE,max_pages = Inf)
      df })})

     #### HERE WE CREATE THE DROP DOWN MENU PART

    output$List1<-renderUI({ 
      my_data=my_data()
      choices<-unique(my_data) 
      #creates State select box object called in ui
        selectInput(inputId = "List1",#name of input
              label = "List1:",#label displayed in ui
              choices =choices,selected = NULL,multiple = TRUE,selectize 
           = T) }) #default choice (not required)


      output$Table1<-renderDataTable({###CREATE TABLE OUTPUT
      data.frame(my_data()) })}

我们现在按以下方式运行该应用程序

         shinyApp(ui,server)

当我们按下运行查询按钮时,应用程序运行,并且从sql数据库动态填充下拉菜单。

我的问题是:是否可以仅通过单击选择下拉框来运行查询。在这种情况下,“运行查询”按钮将变为多余。

xiaofeiyaya 回答:通过单击输入文本框,从R Shiny运行SQL查询

要在没有任何虚拟数据的情况下进行测试很棘手,但如果我理解正确,请进行以下测试:

server <- function(input,output,session) {

    ##### Here the Action button is connected
    my_data <- reactiveVal({
            query2 <- "select C_name from A_table group by C_name"


            df <- query_exec(query2,project = project,useLegacySql = FALSE,max_pages = Inf)
            df })

    #### HERE WE CREATE THE DROP DOWN MENU PART

    output$List1<-renderUI({ 
        my_data=my_data()
        choices<-unique(my_data) 
        #creates State select box object called in ui
        selectInput(inputId = "List1",#name of input
                    label = "List1:",#label displayed in ui
                    choices =choices,selected = NULL,multiple = TRUE,selectize 
                    = T) #default choice (not required)})
    })

        output$Table1<-renderDataTable({###CREATE TABLE OUTPUT
            data.frame(my_data()) })}

尽管这将在启动时运行,并且您在选择下拉菜单时要求您这样做,所以我可能会误解您的用例?

本文链接:https://www.f2er.com/3167113.html

大家都在问