在R Shiny上执行Microsoft SQL查询

时间:2015-10-15 15:06:38

标签: sql-server r shiny

我正在写一个R-Shiny应用程序。有人可以告诉我如何在R Shiny中执行Microsoft SQL查询吗?

这是我到目前为止所做的:

data <- reactive({
    conn <- reactive ({ databaseOpen(serverName="[serverName]", databaseName=[dbName])})
    qr <- reactive ({ SELECT * from myTable })
    res <- reactive ({databaseQuery(conn = conn,query = qr)})
    close(conn)
    View(res)
})

感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

我能够通过在服务器和ui函数之外创建一个函数来调用查询(换句话说,在global.r中)。然后,服务器函数可以使用函数中的一个输入调用该查询函数 这是我的代码:

queryfunction <- function(zipper){

  odbcChannel <- odbcConnect("myconnection")

  querydoc <- paste0("
                SELECT distinct *
                     FROM mydb
                     where substring(nppes_provider_zip,1,2) = '43'
                     and [provider_type] = 'General Practice'
                     ")

   pricetable <- sqlQuery(odbcChannel, querydoc)

   close(odbcChannel)

   pricetable[which(substring(pricetable$nppes_provider_zip,1,5)==zipper),]
}

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


  output$mytable1 <-   renderDataTable(data.table(queryfunction(input$zip)))
})

答案 1 :(得分:0)

我明白了。可以这样做:

server.r

serverfun<-function(input, output){

# Storing values in myData variable
myData <- reactive({

    # Opening database connection
    conn <- databaseOpen(serverName = "myServer",databaseName = "myDB")

    # Sample query which uses some input
    qr <- paste( "SELECT name FROM Genes g WHERE Id = ",input$myId," ORDER BY name")

    # Storing results
    res <- databaseQuery(conn = conn,query = qr) 

    # closing database
    databaseClose(conn)

    # Returning results
    res
})

output$tbTable <- renderTable({
    # Checking if myData is not null
    if(is.null(myData())){return ()}
    # return myData
    myData()

})

ui.r

library("shiny")
shinyUI(

  pageWithSidebar(

    headerPanel("Hide Side Bar example"),
    sidebarPanel(
      textInput("Id", "Enter ID below","1234")
    ),
    mainPanel(
      tabsetPanel(
         tabPanel("Data", tableOutput("tbTable"))
      )
    )
  )
)