问题
Is it possible to run a Shiny app that connects to a sqlite database, and that can make changes and save to that database? My question is similar to this questions - R script do not write in sqlite db if I run the script in shiny but there was no accepted answer, so not sure if it works or not.
回答1:
Yes. It is possible and here is an example:
Create a simple db:
library(RSQLite)
con <- dbConnect(SQLite(), dbname="sample.sqlite")
dbWriteTable(con, "test", data.frame(value1 = letters[1:4], value2 = letters[5:8]))
dbDisconnect(con)
Shiny App:
library(shiny)
library(RSQLite)
runApp(list(
ui = bootstrapPage(
textInput("value1", label = "Value 1"),
textInput("value2", label = "Value 2"),
actionButton("action", label = "Write to DB"),
hr(),
tableOutput("table")
),
server = function(input, output){
data <- eventReactive(input$action, {
con <- dbConnect(SQLite(), dbname="sample.sqlite")
dbWriteTable(con, "test", data.frame(value1 = input$value1, value2 = input$value2, stringsAsFactors = FALSE), append = TRUE)
data <- dbReadTable(con, "test")
dbDisconnect(con)
return(data)
})
output$table <- renderTable(data())
}))
回答2:
Yes it's possible. You can use the RSQlite package. You need to first install SQLite on your machine and create a database. You need to ensure that both the database file AND the folder containing it have write permissions for the shiny user (or whichever user is running shiny apps - the default user is shiny).
This is how you would connect to and save data:
db <- dbConnect(SQLite(), file)
query <- sprintf("INSERT INTO %s (%s) VALUES ('%s')", TABLE_NAME,
paste(names(data), collapse = ", "), paste(data, collapse = "', '"))
dbGetQuery(db, query)
dbDisconnect(db)
Here's a Shiny app that has more complete examples on how to use SQLite and a few other databases with shiny in case it helps. Disclaimer: I wrote that app. http://daattali.com/shiny/google-form-mock/
来源:https://stackoverflow.com/questions/30463302/save-changes-to-sqlite-db-via-shiny