【问题标题】:Import Data from SQL Server To shiny app从 SQL Server 导入数据到闪亮的应用程序
【发布时间】:2018-05-17 02:01:31
【问题描述】:

我使用 RODBC 在 R 中处理来自 SQL Server 的数据,在获得结果后我创建了 ShinyApp 来部署我的结果但是我想从我的 SQL 中获取我的数据直接查询而不将我的结果导出到Excel然后将其导入到shiny,我该怎么做?

Test <- odbcDriverConnect("driver={SQL Server};server=localhost;database=Fakahany;trusted_connection=true")
Orders<- sqlQuery(Test,"
SELECT
  WHWorkOrderHeaderId
, OtherLangDescription
FROM   Warehouse.WHWorkOrderDetails 
   INNER JOIN Warehouse.WHWorkOrderHeader AS WHH
      ON Warehouse.WHWorkOrderDetails.WHWorkOrderHeaderId = WHH.ID 
  INNER JOIN Warehouse.StockItems 
     ON Warehouse.WHWorkOrderDetails.StockItemId = Warehouse.StockItems.Id 
WHERE Type = 'IO'
ORDER BY OtherLangDescription ASC")
#Creating the correlations 
Orders$OtherLangDescription <- as.factor(Orders$OtherLangDescription)
orderList <- unique(Orders$OtherLangDescription) 
ListId <- lapply(orderList, function(x) subset(Orders, OtherLangDescription == x)$WHWorkOrderHeaderId) 
Initial_Tab <- lapply(ListId, function(x) subset(Orders, WHWorkOrderHeaderId %in% x)$OtherLangDescription) 
Correlation_Tab <- mapply(function(Product, ID) table(Product)/length(ID),
                        Initial_Tab, ListId) 
colnames(Correlation_Tab) <- orderList
cor_per<- round(Correlation_Tab*100,2)
DF<-data.frame(row=rownames(cor_per)[row(cor_per)], col=colnames(cor_per)[col(cor_per)], corr=c(cor_per))

这是我的应用代码:

#loading Packages 
library(RODBC)
library(shiny)
library(rsconnect)
ui <- fluidPage(
  titlePanel("Item Correlation"),
  sidebarPanel(
    selectInput("Item2","Select Item",choices= DF$FirstItem),
    h6("Powerd By:"),
    img(src='edrak.png',height='50px',width='110px')
   # ,selectInput("Item","SelectItem",choices= DF$col)
  ),
  mainPanel(
    tableOutput("Itemcorr")
  )
)
server <- function(input,output){
  output$Itemcorr <- renderTable({
    subset(DF, DF$FirstItem == input$Item2)
  })
}

shinyApp(ui, server)

【问题讨论】:

  • 我不明白您所说的“将我的结果导出到 Excel”是什么意思,我没有看到任何导出到 Excel 的内容。对此有不同的解决方案。但我们需要知道您的问题到底出在哪里。
  • 当我使用 sql 连接发布我的应用程序时出现此错误(发生错误应用程序无法启动。)但是当我从 Rstudio 运行应用程序时它工作正常,所以要解决这个问题我将我的结果从 sql 导出到 excel,然后将此 excel 导入我的应用程序。

标签: r shiny rodbc


【解决方案1】:

这应该做你想做的。

library(RODBCext)
library(shiny)

ui <- shinyUI(

  pageWithSidebar(

    headerPanel("Hide Side Bar example"),
    sidebarPanel(
      textInput("CATEGORY", "Enter CATEGORY below"),
      submitButton(text="Submit")
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Data", tableOutput("tbTable"))
      )

    )
  )
)

server <- function(input, output, session)    
{ # NOTE THE BRACE HERE
  myData <- reactive({
    req(input$CATEGORY)

    #connect to database 
    dbhandle = odbcDriverConnect('driver={SQL Server};server=Server_Name;database=Database_Name;trusted_connection=true')

    #build query
    query = "SELECT * FROM [Your_Table] where [CATEGORY] = ?"

    #store results
    res <- sqlExecute(channel = dbhandle, 
                      query = query,
                      data = list(input$CATEGORY),
                      fetch = TRUE,
                      stringsAsFactors = FALSE) 

    #close the connection
    odbcClose(dbhandle)
    #return results
    res
  })

  output$tbTable <- 
    renderTable(myData())

} # AND NOTE THE CLOSING BRACE HERE

shinyApp(ui = ui, server = server)

你也可以考虑一下。

library(shiny)
library(RODBCext)

shinyApp(
  ui = 
    shinyUI(
      fluidPage(
        uiOutput("select_category"),
        tableOutput("display_data")
      #   plotOutput("plot_data")
      )
    ),

  # server needs the function; looks ok
  server = shinyServer(function(input, output, session)
    {
    # A reactive object to get the query. This lets you use
    # the data in multiple locations (plots, tables, etc) without
    # having to perform the query in each output slot.
    QueriedData <- reactive({
        req(input$showDrop)
        ch <- odbcDriverConnect("driver={SQL Server};server=Server_Name;database=DATABASE_NAME;trusted_connection=true")
        showList <- sqlExecute(ch, "SELECT * FROM [Your_Table] WHERE Category = ?",
                               data = list(Category = input$showDrop),
                               fetch = TRUE,
                               stringsAsFactors = FALSE)
        odbcClose(ch)
        showList
      })

    # The select input control.  These can be managed dynamically 
    # from the server, and then the control send back to the UI
    # using `renderUI`
     output$select_category <- renderUI({
         ch <- odbcDriverConnect("driver={SQL Server};server=Server_Name;database=DATABASE_NAME;trusted_connection=true")
         showList <- sqlExecute(ch, "Select Distinct Category From [Your_Table] Order by Category", 
                                fetch = TRUE,
                                stringsAsFactors = FALSE)
         odbcClose(ch)
         selectInput(inputId = "showDrop",
                     label = "Select Asset",
                     showList$Category)
       })

    # Display the data in a table
    output$display_data <- renderTable({
        QueriedData()
      })

    # Display a plot
    # output$plot_data <- 
    #  renderPlot({
    #    plot(QueriedData()) # fill in the plot code you want to use.
    #  })

  })
)

【讨论】:

    猜你喜欢
    • 2012-11-13
    • 2014-04-11
    • 2014-12-22
    • 2013-07-02
    • 2016-07-06
    • 2017-02-11
    • 2016-02-09
    • 1970-01-01
    • 2021-03-31
    相关资源
    最近更新 更多