使用 r 编写和更新 DB2 表

Writing and Updating DB2 tables with r

我不知道如何在 R 中更新现有的 DB2 数据库或更新其中的单个值。

除了非常笼统的信息外,我在网上找不到太多关于这个主题的信息,但没有具体的例子。

        library(RJDBC)

        teachersalaries=data.frame(name=c("bob"), earnings=c(100))




        dbSendUpdate(conn, "UPDATE test1 salary",teachersalaries[1,2])

       teachersalaries=data.frame(name=c("bob",'sally'), earnings=c(100,200))




        dbSendUpdate(conn, "INSERT INTO test1 salary", teachersalaries[which(teachersalaries$earnings>200,] )

您是否尝试过像在其他语言中那样传递常规 SQL 语句?

dbSendUpdate(conn, "UPDATE test1 set salary=? where id=?", teachersalary, teacherid)

dbSendUpdate(conn,"INSERT INTO test1 VALUES (?,?)",teacherid,teachersalary)

基本上,您使用参数标记(那些问号)指定常规 SQL DML 语句,并提供值列表作为逗号分隔的参数。

试试这个,对我来说效果很好。

dbSendUpdate(conn,"INSERT INTO test1 VALUES (?,?)",teacherid,teachersalary)

您只需要像在任何编程语言中一样通过常规 SQL 部分。试试吧。

为了同时更新多行,我构建了以下函数。

我已经用最多 10,000 行的批次对其进行了测试,它运行良好。

# Libraries
library(RJDBC)
library(dplyr)    

# Function upload data into database
db_write_table <- function(conn,table,df){
  # Format data to write
  batch <- apply(df,1,FUN = function(x) paste0("'",trimws(x),"'", collapse = ",")) %>%
  paste0("(",.,")",collapse = ",\n")

  #Build query
  query <- paste("INSERT INTO", table ,"VALUES", batch)

  # Send update
  dbSendUpdate(conn, query)
}

# Push data
db_write_table(conn,"schema.mytable",mydataframe) 

感谢其他作者。