与 RODBC , 有像 sqlUpdate(channel, dat, ...)
这样的函数可以让你传递 dat = data.frame(...)
而不必自己构建SQL 字符串。
但是,使用 R 的 DBI ,我所看到的只是像 dbSendQuery(conn, statement, ...)
这样的函数,它只接受一个字符串 statement
并且没有机会指定一个 data.frame
直接。
那么如何使用带有 DBI 的 data.frame
来UPDATE
?
最佳答案
真的很晚,我的回答,但也许仍然有用......
在 DBI/odbc 包中没有单一的函数(我知道)但是你可以使用准备好的更新语句复制更新行为(它应该比 RODBC 的 sqlUpdate
更快,因为它发送参数值作为批处理到 SQL 服务器:
library(DBI)
library(odbc)
con <- dbConnect(odbc::odbc(), driver="{SQL Server Native Client 11.0}", server="dbserver.domain.com\\default,1234", Trusted_Connection = "yes", database = "test") # assumes Microsoft SQL Server
dbWriteTable(con, "iris", iris, row.names = TRUE) # create and populate a table (adding the row names as a separate columns used as row ID)
update <- dbSendQuery(con, 'update iris set "Sepal.Length"=?, "Sepal.Width"=?, "Petal.Length"=?, "Petal.Width"=?, "Species"=? WHERE row_names=?')
# create a modified version of `iris`
iris2 <- iris
iris2$Sepal.Length <- 5
iris2$Petal.Width[2] <- 1
iris2$row_names <- rownames(iris) # use the row names as unique row ID
dbBind(update, iris2) # send the updated data
dbClearResult(update) # release the prepared statement
# now read the modified data - you will see the updates did work
data1 <- dbReadTable(con, "iris")
dbDisconnect(con)
只有当你有一个主键时才有效,我在上面的例子中使用行名创建了主键,行名是每行加一的唯一数字...
有关我在 DBI dbConnect
语句中使用的 odbc
包的更多信息,请参阅:https://github.com/rstats-db/odbc
关于database - 如何使用 R DBI 传递 data.frame 以进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546468/