如何使用R中的data.frame中的值有条件地更新Database中的行

时间:2016-12-21 14:19:20

标签: sql r postgresql dataframe rpostgresql

我在R中有一个data.frame - 匹配有1000多行

names(matches)
[1] "name"  "c_id"  "fname" "lname" "address" "zip_code"    "Weight"

nrow(matches)
[1] 1253

我有一个postgresql数据库表 - list_m ,包含以下列

db_name,db_cid,db_weight,processing_status,request_id,fname,mname,lname等

我想使用data.frame中的值来更新表中的几列(db_c_id,db_weight和处理状态)的值。

截至目前,我正在循环使用data.frame来创建更新查询,然后运行查询。

for(row in 1:nrow(matches) {   
    query1 <- paste0(query1, "UPDATE list_m SET db_name = ",matches$name[row],", db_weight = ",matches$weight[row],",  processing_status = 'MATCHED'
 WHERE request_id=111 AND db_c_id = '", matches$c_id[row], "';")
}

所以它基本上用

创建一个query1变量
 UPDATE list_m SET db_name = 'HILLARY', db_weight = 51.41, processing_status = 'MATCHED' WHERE request_id=111 AND db_c_id = '1015310246';

 UPDATE list_m SET db_name = 'SANDERS', db_weight = 45.16, processing_status = 'MATCHED' WHERE request_id=111 AND db_c_id = '1015120982';

 ...

 ...

 ...

 UPDATE list_m SET db_name = 'OBAMA', db_weight = 67.11, processing_status = 'MATCHED' WHERE request_id=111 AND db_c_id = '1015110111'; 

 UPDATE list_m SET db_name = 'TRUMP', db_weight = 41.22, processing_status = 'MATCHED' WHERE request_id=111 AND db_c_id = '1013024634';

然后将使用

执行
dbSendStatement(con, query1)

我想要的是通过参数化值来实现这一点......比如

query2 <- "UPDATE list_m SET db_name=?,db_weight=?,processing_status='MATCHED' WHERE request_id=111 and db_c_id=?";

dbSendStatement(con, query2, matches$name, matches$weight, matches$c_id)

此语句应对每行匹配data.frame执行。

1 个答案:

答案 0 :(得分:0)

这可以使用sprintf

进行近似估算
sql_string <- "UPDATE list_m SET db_name = %s, db_weight = %s,  processing_status = 'MATCHED' WHERE request_id=111 AND db_c_id = '%s';"

dbSendStatement(con, paste(sprintf(sql_string, matches$name, matches$weight, matches$c_id), collapse=""))