Search code examples
rrpostgresql

How to append/update a row from a data frame to a table in PostgreSQL db table that has the same columns using RPostgreSQL?


This question is an extension to the question already posted earlier in this forum. I need to append/update a row from a data frame to a table in PostgreSQL db table that has the same columns using RPostgreSQL.I am bale to copy the whole table or use insert command as shown below:

insert into mytable (FName, LName, Age) values (Rosy, Rees, 54)

But, I want to copy row(s) (or a subset from a data frame) directly to RPostgreSQL database table. Any suggestion please?

Example:

Data Frame in R

FName   LName   Age
Rosy    Rees    54

Table in PostgreSQL database before copying the row from data frame

FName   LName   Age
John    Doe     35
Jane    Sanders 32
Robert  Muller  45

Table in PostgreSQL database after copying the row from data frame

FName   LName   Age
John    Doe     35
Jane    Sanders 32
Robert  Muller  45
Rosy    Rees    54

Solution

  • If you made the following table like this in db called 'mydb':

    DROP TABLE IF EXISTS mytable;
    
    CREATE TABLE mytable (
      fname text,
      lname text,
      age integer);
    
    INSERT INTO mytable(fname, lname, age) VALUES
      ('John', 'D.', 35),
      ('Jane', 'S.', 32),
      ('Robert', 'M.', 45);
    

    Then use dbWriteTable in something like this in R to append records form a data frame:

    library(RPostgreSQL)
    
    #load PostgreSQL driver
    drv <- dbDriver("PostgreSQL")
    
    #make connection to the postgres database
    con <- dbConnect(drv, dbname = "mydb",
                 host = "localhost", port = 5432, 
                 user = 'postgres', password = 'postgres')
    
    #insert data into mytable from data frame
    df <- data.frame(fname = "Rosy", lname = "R.", age = 54)
    dbWriteTable(con, "mytable", df, append = TRUE, row.names = FALSE)
    
    dbDisconnect(con)