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

时间:2016-07-22 13:34:17

标签: r postgresql rpostgresql

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

“在postgresqlWriteTable中(conn,name,value,...):数据库中存在表customervalidation:aborting assignTable”

在postgresql中已存在表customervalidation,我试图在此表中插入SampleData.csv的内容。 csv的所有标题都已存在于表中,它们都是小写的。

命令行参数

./script.R batch SampleData.csv yes no

rscripts.R content

#!/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的内容 CSV content here

请帮我识别这里遗漏的错误。

2 个答案:

答案 0 :(得分:2)

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

  • 覆盖指定是否覆盖现有表的逻辑 或不。它的默认值为FALSE。
  • 附加一个指定是否的逻辑 附加到DBMS中的现有表。它的默认值为FALSE。

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

答案 1 :(得分:1)

为避免错误这样写

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