Сохранить RSHINY dataframe в базе данных POSTGRESQL - PullRequest
0 голосов
/ 07 октября 2019

Это блестящее приложение, которое я хотел сохранить в своем фрейме данных в базу данных postgresql. Я пробовал этот код, но он не сохраняет или не показывает вывод. Я не уверен, в чем проблема, я хочу, чтобы, как только пользователь нажал кнопку «Сохранить», он сохраняет данные в фрейме. Я смогу просмотреть таблицу базы данных в разделе вывода таблицы рендеринга. Как я могу исправить этот код для работы

# Set libraries
library(RPostgreSQL)
library(shiny)

# Define the fields we want to save from the form
fields <- c("SN", "Age", "Name")

# Shiny app with two fields that the user can submit data for
shinyApp(
  ui = fluidPage(

    DT::dataTableOutput("responses", width = 300), tags$hr(),

    #textInput("id", "ID", ""),

    #textInput("message", "MESSAGE", ""),

    actionButton("submit", "Submit")
  ),
  server = function(input, output, session) {

    #create dataframe
    df1<- reactive({
      df <- data.frame("id" = 1:2, "Age" = c(21,15), "Name" = c("John","Dora"))
df

    })


    psql <- dbDriver("PostgreSQL")

    saveData <- function(data) {

      # Connect to the database
      pcon <- dbConnect(psql, dbname = "Comparisons", host = "localhost", port = ...., user 
                        = "postgres", password = ".....")

      # Construct the update query by looping over the data fields
      query <- paste0("INSERT INTO public.test_db (SN,Age,Name) VALUES ( $1 )") 

      # Submit the update query and disconnect
      dbSendQuery(pcon, query, params=data[["SN","Age","Name"]]) 
      dbDisconnect(pcon)
    }

    loadData <- function() {
      # Connect to the database
      pcon <- dbConnect(psql, dbname = "Comparisons", host = "localhost", port = ...., user = "postgres", password = "....")

      # Construct the fetching query
      query <- sprintf("SELECT * FROM public.test_db") 

      # Submit the fetch query and disconnect
      data <- dbGetQuery(pcon, query)
      dbDisconnect(pcon)
      data
    }




    # When the Submit button is clicked, save the form data
    observeEvent(input$submit, {
      saveData(df1())
    })

    # Show the previous responses
    # (update with current response when Submit is clicked)
    output$responses <- DT::renderDataTable({
      input$submit
      loadData()
    })     
  })

1 Ответ

0 голосов
/ 09 октября 2019

Ваша функция saveData ожидает, что «data» будет data.frame? Поскольку «df1» является реактивной переменной, я подозреваю, что вам нужно изменить:

saveData(df1())

на:

saveData(df1$df)

, который должен передавать data.frame, а не саму реактивную переменную

...