2

RSQLite在一个闪亮的应用程序中使用这个包。当用户通过应用程序进行时,我需要能够动态更新 sqlite 数据库。我想使用UPDATESQLite 中的语法来实现这一点,但是在尝试为同一用户更新多行时遇到了问题。

考虑以下代码:

# Load libraries
library("RSQLite")

## Path for SQLite db
sqlitePath <- "test.db"

# Create db to store tables
con <- dbConnect(SQLite(),sqlitePath)

## Create toy data
who <- c("jane", "patrick", "samantha", "jane", "patrick", "samantha")
tmp_var_1 <- c(1,2,3, 4, 5, 6)
tmp_var_2 <- c(2,4,6,8,10,12)

# Create original table
users <- data.frame(who = as.character(who), tmp_var_1 = tmp_var_1, tmp_var_2 = tmp_var_2)
users$who <- as.character(users$who)

# Write original table
dbWriteTable(con, "users", users)

# Subset users data
jane <- users[who=="jane",]
patrick <- users[who=="patrick",]
samantha <- users[who=="samantha",]

# Edit Jane's data
jane$tmp_var_1 <- c(99,100)

# Save edits back to SQL (this is where the problem is!)
table <- "users"

db <- dbConnect(SQLite(), sqlitePath)
query <- sprintf(
  "UPDATE %s SET %s = ('%s') WHERE who = %s",
  table, 
  paste(names(jane), collapse = ", "),
  paste(jane, collapse = "', '"),
  "'jane'"
)
dbGetQuery(db, query)

## Load data to check update has worked
loadData <- function(table) {
  # Connect to the database
  db <- dbConnect(SQLite(), sqlitePath)
  # Construct the fetching query
  query <- sprintf("SELECT * FROM %s", table)
  # Submit the fetch query and disconnect
  data <- dbGetQuery(db, query)
  dbDisconnect(db)
  data
}

loadData("users")

在这里,我试图更新条目,Jane以便tmp_var_1更改值,但所有其他列保持不变。针对下面发布的@zx8754 和@Altons 的问题,for 的值query如下:

UPDATE users SET who, tmp_var_1, tmp_var_2 = ('c(\"jane\", \"jane\")', 'c(99, 100)', 'c(2, 8)') WHERE who = 'jane'

问题几乎肯定来自我指定对 RSQlite 的查询的方式。当我运行时,dbGetQuery(db, query)我收到以下错误:

Error in sqliteSendQuery(con, statement, bind.data) : 
  error in statement: near ",": syntax error

任何改进建议都将受到欢迎。

4

0 回答 0