更新r中sqlite表中的选定行

时间:2016-06-10 09:49:40

标签: r sqlite r-dbi

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

请考虑以下代码:

# 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的问题时,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

欢迎任何改进建议。

0 个答案:

没有答案