R语言无法使用postgresqlWriteTable在postgresql中插入

R language unable to insert in postgresql using postgresqlWriteTable

我是 R 的新手,正在尝试在 Postgresql 中插入 R 数据框。每当我尝试执行我的 rscripts.R 时,我都会收到以下错误:

"In postgresqlWriteTable(conn, name, value, ...) : table customervalidation exists in database: aborting assignTable"

Table customervalidation 已经存在于 postgresql 中,我试图在这个 table 中插入 SampleData.csv 的内容。 csv 的所有 headers 都已经存在于 table 中并且它们都是小写的。

命令行参数

./script.R batch SampleData.csv yes no

rscripts.R内容

#!/usr/bin/Rscript

options(echo=TRUE) # if you want see commands in output file
args <- commandArgs(trailingOnly = TRUE)
print(args)
# trailingOnly=TRUE means that only your arguments are returned, check:
# print(commandsArgs(trailingOnly=FALSE))

batchIndicator <- tolower(args[1])
filename <- args[2]
isHeaderPresent <-args[3]
isRunTheBatch<-args[4]
rm(args)
#Library files
library(RPostgreSQL)
#now check whether it is immediate or batch.
# if it is immediate then real time prediction needs to prepare.
# if it is batch then whole batch set needs to prepare and keep the results in a separate file.
if(isHeaderPresent == "yes")
{
  header = TRUE
}else
{
  if(isHeaderPresent == "no"){

    header = FALSE
  }
}

  print(paste("Processing for Batch mode for filename ", filename))
  # Start body for other function
  data <-read.csv(filename,header = header, sep=",")
  drv <- dbDriver("PostgreSQL")
  con <- dbConnect(PostgreSQL(), dbname = "customervalidation", host = "localhost", port =5432 , user = "user", password = "pwd")
  dbWriteTable(con,"customervalidation",data,row.names=FALSE)
  #end body for other function

以及SampleData.csv的内容

请帮助我找出这里缺少的错误。

错误是不言自明的:table 已经存在。如果您查看 manual,您会看到有两个选项:

  • overwrite a logical 指定是否覆盖现有的 table 或不。它的默认值为 FALSE。
  • 追加逻辑指定是否 附加到 DBMS 中现有的 table。它的默认值为 FALSE。

您必须将其中一项指定为 TRUE。

为了避免错误这样写

     dbWriteTable(con,"customervalidation",data,row.names=FALSE,append = TRUE)