通过Shiny应用程序更新表数据库SQL Server中的数据

时间:2019-02-08 07:58:23

标签: r sql-server shiny shiny-reactivity

我想开发一个有光泽的应用程序,而我刚开始使用R(所以可以想象...)。

现在,我设法将闪亮的应用程序(通过DBI库)连接到Microsoft SQL Server,并显示了该数据库上的3个表之一。

目标是允许用户单击行并更改其上的数据。在这种情况下,只有一列仅使用1或0作为值。我设法创建了按钮,但是我无法允许该应用程序单击该行并更改数据。

这是我到目前为止的代码:

# Load libraries
library(shiny)
library(shinydashboard)
library(RODBC)
library(odbc)
library(pool)
library(DBI)


# connect database
con = DBI::dbConnect(odbc::odbc(), 
                     Driver = "SQL Server", 
                     Server = "MyServer", 
                     Database = "test", 
                     Trusted_Connection = "True")


# Start the dashboard
ui = dashboardPage(
  dashboardHeader(title = 'My_first_App'),
  
  dashboardSidebar(
    sidebarMenu(
      menuItem("Tables", tabName = "tables", icon = icon("th")),
      menuItem("Perfomance Dashboard", tabName = "dashboard", icon = icon("dashboard"))
    )
  ),
  
  dashboardBody(
    tabItems(
      # item for tables(Table_1 in this case)
      tabItem(tabName = "tables",
              fluidRow(
                box(tableOutput("tbl")),

                # Tick box to allow the user to change data
                box(title = "Column_to_change",
                    checkboxInput("Column_to_change", "Column_to_change", FALSE)),
                
                #action buttons
                actionButton("submit", "Submit"),
                actionButton("new", "New")
              ))
    )
  )
)


server = function(input, output) {
  
  # We get the Table_1 to show all of it
  output$tbl = renderTable({
    sql = "SELECT * FROM Table_1;"
    query = sqlInterpolate(con, sql, id = input$ID)
    dbGetQuery(con, query)
    
  })
  
  
}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:0)

您可以使用DTEdit包来创建可编辑的高质量文件并在ShinyApp中查找数据表。语法安静且易于使用。

https://github.com/jbryer/DTedit

my.insert.callback <- function(data, row) {
    mydata <- rbind(data, mydata)
    return(mydata)
}

my.update.callback <- function(data, olddata, row) {
    mydata[row,] <- data[1,]
    return(mydata)
}

my.delete.callback <- function(data, row) {
    mydata[row,] <- NULL
    return(mydata)
}


DTedit::dtedit(input, output,
       name = 'mycontacts',
       thedata = mydata,
       edit.cols = c('name', 'email', 'useR', 'notes'),
       edit.label.cols = c('Name', 'Email Address', 'Are they an R user?', 'Additional notes'),
       input.types = c(notes='textAreaInput'),
       view.cols = c('name', 'email', 'useR'),
       callback.update = my.update.callback,
       callback.insert = my.insert.callback,
       callback.delete = my.delete.callback)