如何从 R 将单行数据写入 postgresql table?
How do I write a single row of data into a postgresql table from R?
我在 postgresql 数据库 mydatabase
中有一个 table myschema.fruits
。在 R 脚本中,我想在 os 我的脚本末尾插入一行 table。 table 行有 3 列 type
、taste
和 color
。 Those 我的 R 脚本中有 3 个不同的变量,它们具有相同的变量名称,如下所示:
type <- "Apple"
taste <- "Sweet"
color <- "Red"
我想使用 RPostgreSQL driver 执行此插入,但我不知道该怎么做?
如有必要,请更改主机、端口、用户并添加密码。
第一个选项:将数据框附加到 table
dt2insert = data.frame(type = "Apple",
taste = "Sweet",
color = "Red",
stringsAsFactors = FALSE)
con = dbConnect(dbDriver("PostgreSQL"),dbname = "mydatabase",
host = "localhost", port = 5432,
user = "postgres")
dbWriteTable(con, name = c("myschema","fruits"), value = dt2insert,append=TRUE,row.names=FALSE,overwrite=FALSE)
dbDisconnect(con)
第二个选项:使用 INSERT INTO 命令
type <- "Apple"
taste <- "Sweet"
color <- "Red"
qry = paste0("INSERT INTO myschema.fruits VALUES ('",type,"','",taste,"','",color,"');")
con = dbConnect(dbDriver("PostgreSQL"),dbname = "mydatabase",
host = "localhost", port = 5432,
user = "postgres")
dbSendQuery(con,qry)
dbDisconnect(con)
作为使用 INSERT INTO 命令的替代方法,请考虑使用低级 postgresqlExecStatement
函数,它允许对查询进行参数化。这样做的主要优点是您不必为适当的数据类型手动构造查询字符串,在这种情况下您可以省略额外的引号 '
:
type <- "Apple"
taste <- "Sweet"
color <- "Red"
con = dbConnect(dbDriver("PostgreSQL"),dbname = "mydatabase",
host = "localhost", port = 5432,
user = "postgres")
tmp <- postgresqlExecStatement(con,
'insert into myschema.fruits VALUES (, , )',
list(type, taste, color))
dbClearResult(tmp)
dbDisconnect(con)
我在 postgresql 数据库 mydatabase
中有一个 table myschema.fruits
。在 R 脚本中,我想在 os 我的脚本末尾插入一行 table。 table 行有 3 列 type
、taste
和 color
。 Those 我的 R 脚本中有 3 个不同的变量,它们具有相同的变量名称,如下所示:
type <- "Apple"
taste <- "Sweet"
color <- "Red"
我想使用 RPostgreSQL driver 执行此插入,但我不知道该怎么做?
如有必要,请更改主机、端口、用户并添加密码。
第一个选项:将数据框附加到 table
dt2insert = data.frame(type = "Apple",
taste = "Sweet",
color = "Red",
stringsAsFactors = FALSE)
con = dbConnect(dbDriver("PostgreSQL"),dbname = "mydatabase",
host = "localhost", port = 5432,
user = "postgres")
dbWriteTable(con, name = c("myschema","fruits"), value = dt2insert,append=TRUE,row.names=FALSE,overwrite=FALSE)
dbDisconnect(con)
第二个选项:使用 INSERT INTO 命令
type <- "Apple"
taste <- "Sweet"
color <- "Red"
qry = paste0("INSERT INTO myschema.fruits VALUES ('",type,"','",taste,"','",color,"');")
con = dbConnect(dbDriver("PostgreSQL"),dbname = "mydatabase",
host = "localhost", port = 5432,
user = "postgres")
dbSendQuery(con,qry)
dbDisconnect(con)
作为使用 INSERT INTO 命令的替代方法,请考虑使用低级 postgresqlExecStatement
函数,它允许对查询进行参数化。这样做的主要优点是您不必为适当的数据类型手动构造查询字符串,在这种情况下您可以省略额外的引号 '
:
type <- "Apple"
taste <- "Sweet"
color <- "Red"
con = dbConnect(dbDriver("PostgreSQL"),dbname = "mydatabase",
host = "localhost", port = 5432,
user = "postgres")
tmp <- postgresqlExecStatement(con,
'insert into myschema.fruits VALUES (, , )',
list(type, taste, color))
dbClearResult(tmp)
dbDisconnect(con)