Сохранение данных, записанных в функции textinput, в базе данных mysql - PullRequest
0 голосов
/ 02 мая 2019

Я хочу сохранить данные в базе данных mysql, которые я напишу в кнопке ввода текста. Когда я нажму кнопку сохранения сценария, он должен сохранить это имя в моей таблице базы данных.

Мой код:

library("shiny")
library("shinydashboard")
library(DBI)
pool <- dbPool(drv = RMySQL::MySQL(),dbname = "demo",host = 
"db.cr7lkdht.us-east-2.rds.amazonaws.com",username = "krtik",password 
= "123456", port = 3306)


ui <- fluidPage(


  actionButton("create_scenario", "Create Scenario"),
  actionButton("load_scenario","load scenario"),
  uiOutput("input"),
 uiOutput("inputs")
)

server <- function(input, output,session) {

  observeEvent(input$create_scenario,{

    output$input <- renderUI({
      mainPanel(     
        textInput("txtInput","Enter Scenario Name"),
    textOutput("sname"),
                  actionButton("save","save scenario")
   )

})
output$sname <- renderText({
  input$txtInput
})



observeEvent(input$save,{
  conn <- poolCheckout(pool)
  dbSendQuery(conn,"insert into scenario(name) values ('output$sname');")

})


})

  observeEvent(input$load_scenario,{

output$inputs <- renderUI({
  # textInput("txtInput","Enter Scenario Name","Enter name as scenario  
  #(number of senario created +1)")
  dashboardPage(
    dashboardHeader(title = "Basic dashboard"),
    dashboardSidebar(),
    dashboardBody(
      # Boxes need to be put in a row (or column)
      fluidRow(
        box(plotOutput("plot1", height = 250)),

        box(
          title = "Controls",
          sliderInput("slider", "Number of observations:", 1, 100, 50)
        ))))


} )
histdata <- rnorm(500)
output$plot1 <- renderPlot({
  data <- histdata[seq_len(input$slider)]
  hist(data)
})


  })
}
shinyApp(ui, server) 

Моя база данных выглядит так

 select * from scenario;
+----------------------+-------+
| name                 | s_key |
+----------------------+-------+
| a                    |     1 |
| b                    |     2 |
| sname                |     3 |
| renderText({
 in |     4 |
 +----------------------+-------+

Я установил s_key как auto_increment.please игнорировать строку renderText.Кто-нибудь может мне помочь, как я могу поместить имя, которое я печатаю в моем приложении в моей базе данных.

1 Ответ

0 голосов
/ 07 мая 2019

Для этого я конвертировал данные, набранные в selectInput , в фрейм данных и выгружал данные в базу данных. Для выгрузки в базу данных я использовал библиотеку pool и установил s_key как auto_increment . Вот код

library("shiny")
library("shinydashboard")
library("pool")
library(DBI)
 pool <- dbPool(drv = RMySQL::MySQL(),dbname = "demo",host = "db.crjwjdht.us- 
east-2.rds.amazonaws.com",username = "ka",password = "12345", port = 3306)

    mychoices = dbGetQuery(pool,"select x from scenario;")
 #mychoices = as.character(mychoices)
 ui <- fluidPage(


  actionButton("create_scenario", "Create Scenario"),
 actionButton("load_scenario","load scenario"),
selectInput('options', label="mtcars column variables", choices=myChoices, multiple = 
  TRUE),
 verbatimTextOutput("selected"), # to display the selected choices by user

 uiOutput("input"),
      uiOutput("inputs"),
  uiOutput("inputss")
)

server <- function(input, output,session) {

     observeEvent(input$create_scenario,{

      output$input <- renderUI({
      mainPanel(     
        textInput("txtInput","Enter scenario name"),
           textOutput("sname"),
                         actionButton("save","save_scenario")
      )

   })


   output$sname <- renderText({
     input$txtInput
   })



   observeEvent(input$save,{
    #  conn <- poolCheckout(pool)
    #  dbSendQuery(conn,"insert into scenario (name) values (", output$sname <- 
 renderText({
     #  input$txtInput
      #}),");")
     dd <- data.frame(x = input$txtInput,row.names = FALSE)
      print(dd)
     dbWriteTable(pool,"scenario",dd,append = TRUE)
    # values$dd <- rbind(values$dd,data.frame(Enter = input$txtInput))
   })

    })
#  mychoices = dbGetQuery(pool,"select * from scenario;")
 # mychoices = dbGetQuery(pool,"select x from scenario;")
 # print(mychoices)



   # print(mychoices)
 observe({
   updateSelectInput(
      session, 'options', choices = mychoices
     #selected = if(input$all) myChoices
   )
 })

  output$selected <- renderText({
   paste(input$options, collapse = ",")
  })


  observeEvent(input$load_scenario,{

    output$inputs <- renderUI({
      # textInput("txtInput","Enter Scenario Name","Enter name as scenario  
      #(number of senario created +1)")
     dashboardPage(
        dashboardHeader(title = "Basic dashboard"),
    dashboardSidebar(),
    dashboardBody(
      # Boxes need to be put in a row (or column)
      fluidRow(
        box(plotOutput("plot1", height = 250)),

        box(
          title = "Controls",
          sliderInput("slider", "Number of observations:", 1, 100, 50)
        ))))


} )
histdata <- rnorm(500)
output$plot1 <- renderPlot({
  data <- histdata[seq_len(input$slider)]
  hist(data)
    })


  })
}
shinyApp(ui, server)
...