How to update rows in Database with values from data.frame in R conditionally

懵懂的女人 提交于 2019-12-12 06:38:34

问题


I've a data.frame in R - matches with some 1000+ rows

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

nrow(matches)
[1] 1253

I have a postgresql database table - list_m with following columns

db_name, db_cid, db_weight, processing_status, request_id, fname, mname, lname, etc.

I want to udpate the values of only few columns (db_c_id, db_weight and processing status) in the table using values from the data.frame.

As of now, I am looping over the data.frame to create the update queries and then run the queries.

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], "';")
}

so it basically creates a query1 variable with

 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';

which will then be executed using

dbSendStatement(con, query1)

What I would like is to do this by parameterizing the values.. something like

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)

this statement should execute for each row of matches data.frame.


回答1:


This could be closely approximated using 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=""))


来源:https://stackoverflow.com/questions/41264942/how-to-update-rows-in-database-with-values-from-data-frame-in-r-conditionally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!