rpostgreSQL:根据时间覆盖数据

rpostgreSQL: Overwrite the data based on the time

我们的财务团队正在使用闪亮的应用程序每月将 csv 文件上传到 postegreSQL。 有时,他们需要修改数据,然后重新上传。

让我们举一些例子让问题更容易理解:

# Retrieve data from PostgreSQL
>monthly_expense <- dbGetQuery(con, "SELECT * from expense_table2")
>monthly_expense
>month   type  USD
 201605    A   200
 201605    B   300
 201606    A   105
 201606    B   200

 # Produce new 201606 data
 >month<-c("201606", "201606")
 >type<-c("A", "B")
 >USD<-c(150, 250)
 >new_data<-data.frame(month, type, USD )
 >new_data
    month    type USD
 1  201606    A   150
 2  201606    B   250

那么如何用新数据替换201606数据呢? 我认为应修改以下命令以指定应覆盖 2016 年的数据:

 dbWriteTable(con, "expense_table2", value = new_data, append=T, overwrite = TRUE)  

考虑使用 dbSendQuery:

的更新查询
sqlstrings <- paste0("UPDATE expense_table2 SET USD = ", newdata$USD , " 
                      WHERE month='", newdata$month, "' AND type='", newdata$type, "';")

queryruns <- lapply(sqlstrings, function(x) dbSendQuery(con, x))

或者,更新现有数据框,然后用 dbWriteTable:

覆盖 Postgres 的数据库 table
index <- match(monthly_expense$month, new_data2$month)
monthly_expense[index, 2:3] <- new_data2[2:3]

dbWriteTable(con, "expense_table2", value = monthly_expense, append=T, overwrite = TRUE) 

此外,rbind 未更新的行到新数据并将其推送到数据库:

newdata <- rbind(monthly_expense[!(monthly_expense$month %in% newdata$month),],
                 newdata)

dbWriteTable(con, "expense_table2", value = new_data, append=T, overwrite = TRUE)