[英]How do I write a single row of data into a postgresql table from R?
I have a table myschema.fruits
in a postgresql database mydatabase
. 我在postgresql数据库mydatabase
有一个表myschema.fruits
。 From within an R script I would like to insert a single row to that table, at the end os my script. 从R脚本中我想在该表中插入一行,最后是我的脚本。 The table row has 3 columns type
, taste
and color
. 表格行有3列type
, taste
和color
。 Those I have in 3 different variables in my R script with same variable names like so: 我在R脚本中的3个不同变量中具有相同变量名称的变量如下:
type <- "Apple"
taste <- "Sweet"
color <- "Red"
I would like to use the RPostgreSQL driver to perform this insert, but I can't figure out how to do it? 我想使用RPostgreSQL驱动程序来执行此插入,但我无法弄清楚如何做到这一点?
As an alternative method using the INSERT INTO command, consider using the low level postgresqlExecStatement
function, which allows parametrization of the query. 作为使用INSERT INTO命令的替代方法,请考虑使用低级postgresqlExecStatement
函数,该函数允许查询的参数化。 The primary advantage of this is that you don't have to manually construct the query string for the appropriate data types, in this case you can leave out the extra quotation marks '
: 这样做的主要优点是您不必手动构造适当数据类型的查询字符串,在这种情况下,您可以省略额外的引号'
:
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 ($1, $2, $3)',
list(type, taste, color))
dbClearResult(tmp)
dbDisconnect(con)
Please change host, port, user and add password if necessary. 如有必要,请更改主机,端口,用户并添加密码。
First option: appending a data frame to the 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)
Second option: using INSERT INTO command 第二个选项:使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.