【问题标题】:Updating Local Postgresql Database with R, using Update or Insert使用 R 更新本地 Postgresql 数据库,使用 Update 或 Insert
【发布时间】:2016-08-31 15:24:09
【问题描述】:

我正在建立一个本地服务器,以便在本地和远程与托管表进行交互。我已经通过Rpostgresql成功连接到本地db,并且可以查询和写表了。

我还没有找到任何关于在 R 中使用数据框行更新表的有前途的帖子。 (对于我的功能,这意味着添加新的观察行,假设我每周更新数字)。

假设 mtcars 表作为 postgres 表上传如下:

              postgrestable = mtcars
              postgrestable$key = rownames(postgrestable)
              postgrestable = postgrestable[, c(12, 1:2)]
              head(postgrestable)

我在 R 中有以下数据框:

               key = c("MazdaRX4", "Toyota H5", "Chevy Delirium") 
               mpg = c(21, 22, 31) 
               cyl = c(6, 4, 6) 
               df = data.frame(key, mpg, cyl)  
               head(df)

下面是代码的开头:

库(RPostgreSQL)

               # create a connection
               # save the password that we can "hide" it as best as we can                      by collapsing it
                pw <- {
                "abc123"
                 }

                # loads the PostgreSQL driver
                drv <- dbDriver("PostgreSQL")
                # creates a connection to the postgres database
                # note that "con" will be used later in each connection to  the database
                 con <- dbConnect(drv, dbname = "mydb",
                 host = "localhost", port = 5432,
                 user = "postgres", password = pw)
                  rm(pw) # removes the password

                   # check for the cartable
                   dbExistsTable(con, "postgrestable")
                   #TRUE

                   #update table (not sure how to structure this)
                   sql <- "INSERT INTO postgrestable
                   VALUES ("df")"

我知道在这种情况下行名是不同的,但为了简单起见,我们假设它们是相同的。我将如何将三行'df'插入'postgrestable'?请注意,我做了一个重复项,因为我想考虑到可能存在重复条目的事实。 感谢帮助的家伙

【问题讨论】:

    标签: r postgresql


    【解决方案1】:

    考虑通过 sql 语句列表运行lapply()

    sqllist <- paste0("INSERT INTO postgretable(key, mpg, cyl) ",
                      "VALUES('",df$key,"',",df$mpg,",",df$cyl,")")
    
    appendAction <- lapply(sqllist, function(x) dbSendQuery(con, x))
    

    【讨论】:

      【解决方案2】:

      这是我的一个项目中的一个(稍作调整的)辅助函数:

      insertIntoTable <- function(con, dat) {
          for (i in seq_len(nrow(dat))) {
              sql <- paste0("insert into table values('", 
                            dat[i,"symbol"], "', ",
                            dat[i,"volume"], ", ",
                            "'abc', 'def', 'ghi', ",
                            dat[i,"cost"], ", '", 
                            dat[i,"date"], "');")
              dbSendQuery(con, sql)
          }
          invisible(NULL)
      }
      

      您可以先打印命令字符串并手动运行测试。

      如果是update而不是insert,您可以添加自己的逻辑

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-24
        • 2011-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-22
        相关资源
        最近更新 更多