我有一个需要在sqlite上运行的事务。该交易包括几个查询。如果单独构建(逐行)它可以工作,但它需要n次调用dbSendQuery。它会慢慢减慢代码的速度。
理想代码应如下所示,但多行查询失败:
library("RSQLite")
con <- dbConnect(RSQLite::SQLite(), dbname="test.db")
dbSendQuery(con, paste("CREATE TABLE Variables (Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT)"))
dbSendQuery(con, paste("INSERT INTO Variables (Name) VALUES ('newid');"))
dbSendQuery(con, paste("BEGIN IMMEDIATE TRANSACTION;",
"UPDATE Variables SET TextValue = '0' WHERE Name = 'newid';",
"UPDATE Variables SET RealValue = 0 WHERE Name = 'newid';",
"UPDATE Variables SET IntegerValue = 0 WHERE Name = 'newid';",
"COMMIT;",sep=" "))
a <- dbFetch(dbSendQuery(con, paste("SELECT * FROM _Variables;")))
dbSendQuery(con, paste("COMMIT;"))
答案 0 :(得分:4)
考虑处理交易的RSQLite方法:dbBegin()
和dbCommit()
(w / dbRollback
(任何错误))。甚至考虑将所有UPDATE
语句合并为一个:
library("RSQLite")
con <- dbConnect(RSQLite::SQLite(), dbname="test.db")
dbSendStatement(con, "CREATE TABLE [Variables] ([Name] TEXT PRIMARY KEY, [RealValue] REAL, [IntegerValue] INTEGER, [BlobValue] BLOB, [TextValue] TEXT)")
dbSendStatement(con, "INSERT INTO [Variables] ([Name]) VALUES ('newid')")
dbBegin(con)
tryCatch({
dbSendStatement(con, "UPDATE [Variables] SET TextValue = '0', RealValue = 0, IntegerValue = 0 WHERE [Name] = 'newid'")
}, error=function(e) dbRollback(con))
dbCommit(con)
a <- dbGetQuery(con, "SELECT * FROM [Variables]")
您甚至可以将UPDATE
语句合并到一个查询中: