1

我有一个需要在 sqlite 上运行的事务。事务包括几个查询。如果单独构建(逐行)它可以工作,但它需要调用 dbSendQuery n 次。它使代码变慢了很多。

理想的代码应该是这样的,但是多行查询失败:

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;"))
4

1 回答 1

4

考虑RSQLite方法:dbBegin()dbCommit()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语句组合成一个查询:

于 2017-01-17T23:23:10.147 回答