2

I am writing an R-Shiny app. Can some one tell me how to execute a Microsoft SQL query in R Shiny ?

This is what I have done so far:

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)
})

Any help is appreciated !

3
  • Look here, here Commented Oct 15, 2015 at 15:11
  • Aren't above examples for MySQl? I am looking for connecting to Microsoft SQL. Commented Oct 15, 2015 at 18:56
  • Those would be set-up in a similar manner, if you connect to them via Data Sources(ODBC) on windows Commented Oct 16, 2015 at 7:01

2 Answers 2

1

I was able to call a query by creating a function outside of the server and ui functions (in other words, in a global.r). Then the server function could call that query function using one of the inputs in the function.
Here is my code:

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)))
})
Sign up to request clarification or add additional context in comments.

Comments

0

I figured it out. It can be done as:

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"))
      )
    )
  )
)

1 Comment

Hi what is the package that you used for databaseOpen?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.