将数据帧保存到Postgresql数据库

将数据帧保存到Postgresql数据库,r,shiny,shinydashboard,shiny-server,R,Shiny,Shinydashboard,Shiny Server,您好,朋友们,这是我的闪亮应用程序,带有虚拟数据框,我正试图将其保存在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 sub

您好,朋友们,这是我的闪亮应用程序,带有虚拟数据框,我正试图将其保存在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()
    })     
  })
#设置库
库(RPostgreSQL)
图书馆(闪亮)
#定义要从表单保存的字段

字段您使用
dbSendQuery
而不是
DBI::dbAppendtable
DBI::dbCreateTable
DBI::dbWriteTable
中的一个是否有原因?我认为它们会是更安全(甚至更快)的替代方案。@r2evans您能帮助我如何在该代码上实现它吗?首先,
data[[“SN”,“Age”,“Name”]
无法工作,这不是
[[[
如何工作。其次,使用
DBI::dbAppendTable(con,“tablename”,data)
是直截了当的。我建议您先尝试手动操作,看看它是如何工作的,然后将其调整到您的应用程序中。