Importing and Downloading Data from SQL Server to Shiny

Hello,

I'm trying to learn R's Shiny functions. I'm currently reading through this manual and I'm trying to recreate this example. The example is simply writing an application which allows you to select a specific dataset and download it. I'm trying to follow the examples exact coding format but I would like to pull data from a SQL server, store it in my app and allow others to download it. I added the SQL call functions into the code below (above the reactive function).

I tried executing my code below and it just runs without producing any feedback errors or outputs. I assume my issue is the way I'm calling the dataset in the server portion of my code. Any feedback on my code or additional resources to use would be much appreciated. Thanks!

library(shiny)
library(RODBC)

conn <- odbcConnect("xyz")
query <- " SELECT XYZ..."

dataset <- sqlQuery(channel = conn, query = query)

ui <- fluidPage(
  
  # App title ----
  titlePanel("Downloading Data"),
  
  # Sidebar layout with input and output definitions ----
  sidebarLayout(
    
    # Sidebar panel for inputs ----
    sidebarPanel(
      
      # Input: Choose dataset ----
      selectInput("dataset", "Choose a dataset:",
                  choices = c("climate")),
      
      # Button
      downloadButton("downloadData", "Download")
      
    ),
    
    # Main panel for displaying outputs ----
    mainPanel(
      
      tableOutput("table")
      
    )
    
  )
)

server <- function(input, output) {
  
 # Reactive value for selected dataset ----
datasetInput <- reactive({
  switch(input$dataset,
         "climate" = dataset)
})

# Table of selected dataset ----
output$table <- renderTable({
  datasetInput()
})

# Downloadable csv of selected dataset ----
output$downloadData <- downloadHandler(
  filename = function() {
    paste(input$dataset, ".csv", sep = "")
  },
  content = function(file) {
    write.csv(datasetInput(), file, row.names = FALSE)
  }
)

}

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.