2016-08-31 9 views
0

私は、ホストされたテーブルとローカルおよびリモートでやりとりするためにローカルサーバを確立しようとしています。私は正常にRpostgresqlを介してローカルDBに接続し、私はクエリとテーブルを書くことができます。更新または挿入を使用してRを使用してローカルのPostgreSQLデータベースを更新する

データフレームの行がR. のテーブルを更新することについて有望な投稿は見つかりませんでした(これは、新しい観測列を追加することを意味します。

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

及びiは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) 

コードの始まりである:

mtcarsテーブルは以下のようにPostgresのテーブルとしてアップロードされると仮定

ライブラリ(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")" 

このケースではrownamesが違うことは分かっていますが、簡単にするために同じ名前であると仮定しています。 'df'の3行を 'postgrestable'に挿入するにはどうすればいいですか?私は反復的なエントリがあるかもしれないという事実を考慮に入れたいので、私は繰り返しました。 はここでヘルプみんな

答えて

0

に感謝私のプロジェクトから(微調整)ヘルパー関数です:

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

0

は、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)) 
関連する問題