将RSHINY数据框保存到POSTGRESQL数据库中

问题描述 投票:0回答:1

这个我想将数据框保存到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()
    })     
  })
r postgresql shiny shinydashboard
1个回答
0
投票

您的saveData函数是否希望“数据”为data.frame?由于“ df1”是一个反应变量,我怀疑您需要更改:

saveData(df1())

至:

saveData(df1$df)

应该传递d​​ata.frame而不是反应变量本身

© www.soinside.com 2019 - 2024. All rights reserved.