如何使用 RPostgreSQL append/update 从数据框到具有相同列的 PostgreSQL 数据库 table 中的 table 行?
How to append/update a row from a data frame to a table in PostgreSQL db table that has the same columns using RPostgreSQL?
此问题是对已在本论坛 earlier 上发布的问题的扩展。我需要从数据框 append/update 一行到 PostgreSQL 数据库 table 中的 table 具有相同的列,使用 RPostgreSQL.I am bale 复制整个 table 或使用如下所示的插入命令:
insert into mytable (FName, LName, Age) values (Rosy, Rees, 54)
但是,我想将行(或数据框中的子集)直接复制到 RPostgreSQL 数据库 table。有什么建议吗?
示例:
R 中的数据帧
FName LName Age
Rosy Rees 54
Table 在从数据框复制行之前在 PostgreSQL 数据库中
FName LName Age
John Doe 35
Jane Sanders 32
Robert Muller 45
Table 从数据框复制行后在 PostgreSQL 数据库中
FName LName Age
John Doe 35
Jane Sanders 32
Robert Muller 45
Rosy Rees 54
如果您在名为 'mydb' 的数据库中像这样创建了以下 table:
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);
然后在 R 中像这样使用 dbWriteTable
从数据框追加记录:
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)
此问题是对已在本论坛 earlier 上发布的问题的扩展。我需要从数据框 append/update 一行到 PostgreSQL 数据库 table 中的 table 具有相同的列,使用 RPostgreSQL.I am bale 复制整个 table 或使用如下所示的插入命令:
insert into mytable (FName, LName, Age) values (Rosy, Rees, 54)
但是,我想将行(或数据框中的子集)直接复制到 RPostgreSQL 数据库 table。有什么建议吗?
示例:
R 中的数据帧
FName LName Age
Rosy Rees 54
Table 在从数据框复制行之前在 PostgreSQL 数据库中
FName LName Age
John Doe 35
Jane Sanders 32
Robert Muller 45
Table 从数据框复制行后在 PostgreSQL 数据库中
FName LName Age
John Doe 35
Jane Sanders 32
Robert Muller 45
Rosy Rees 54
如果您在名为 'mydb' 的数据库中像这样创建了以下 table:
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);
然后在 R 中像这样使用 dbWriteTable
从数据框追加记录:
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)