您好,朋友们是我尝试将虚拟数据框保存到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()
})
})
我的意图是在处理完表格后,我应该通过操作按钮将其提交,该按钮会自动保存到PostgreSQL数据库中。请帮助我了解我在这里做错了什么。我想将表保存到数据库中,然后能够通过渲染数据表输出查看它。