我使用下面的语句通过以下语句更新到postgreSQL数据库
update users
set col1='setup',
col2= 232
where username='rod';有没有人能指导我怎么用R呢?我不擅长R
提前感谢你的帮助
发布于 2019-11-21 01:14:34
因为您没有提供任何数据,所以我在这里创建了一些数据。
users <- data.frame(username = c('rod','stewart','happy'), col1 = c(NA_character_,'do','run'), col2 = c(111,23,145), stringsAsFactors = FALSE)要使用base R进行更新:
users[users$username == 'rod', c('col1','col2')] <- c('setup', 232)如果您更喜欢data.table包提供的更明确的语法,您可以执行:
library(data.table)
setDT(users)
users[username == 'rod', `:=`(col1 = 'setup', col2 = 232)]要通过RPostgreSQL更新数据库,首先需要创建数据库连接,然后简单地将查询存储在字符串中,例如
con <- dbConnect('PostgreSQL', dbname = <your database name>, user=<user>, password= <password>)
statement <- "update <schema>.users set col1='setup', col2= 232 where username='rod';"
dbGetQuery(con, statement)
dbDisconnect()注意:根据您的PostgreSQL配置,您可能还需要设置搜索路径dbGetQuery(con, 'set search_path = <schema>;')
我更熟悉RPostgres,所以您可能需要仔细检查一下PostgreSQL包的语法和小插曲。
编辑:与dbSendQuery相比,RPostgreSQL似乎更喜欢dbGetQuery发送更新和命令
https://stackoverflow.com/questions/58957156
复制相似问题