这个闪亮的应用程序我想将数据框保存到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()
})
})
答案 0 :(得分:0)
您的saveData函数是否希望“数据”为data.frame?由于“ df1”是一个反应变量,我怀疑您需要更改:
saveData(df1())
收件人:
saveData(df1$df)
应该传递data.frame而不是反应变量本身