R - RPostgreSQL Package - dbWriteTable到非默认模式,目标表包含比数据框更多的字段



事件

我试图将R数据框df的内容复制到位于模式schema_name的PostgreSQL表table_name。默认情况下,PostgreSQL将把表写入public模式,我不想更改此设置。这种传输的两个独特方面是:

  1. 在非默认模式下写表;和
  2. 数据帧df包含的字段数比table_name少。 df中包含的所有字段在table_name中都存在。

What I've try

我首先尝试使用RPostgreSQL包中的dbWriteTable,方法是:

dbWriteTable(con, c("schema_name","table_name"), df, append = T)

导致以下异常:

Error in postgresqlgetResult(new.con) : 
  RS-DBI driver: (could not Retrieve the result : ERROR:  missing data for column "extra_col"
CONTEXT:  COPY df, line 1: " [removed contents] "

然后我尝试从caroline包(前面提到的dbWriteTable函数的包装器)中提取dbWriteTable2,但是上面使用的非默认模式破解似乎不起作用:

dbWriteTable2(con, c("schema_name","table_name"), df, append = T, add.id = FALSE)

创建以下异常:

creating NAs/NULLs for for fields of table that are missing in your df 
Error in postgresqlExecStatement(conn, statement, ...) : 
RS-DBI driver: (could not Retrieve the result : ERROR:  relation "schema_name" does not exist 
LINE 1: SELECT * FROM schema_name ORDER BY id DESC LIMIT 1

在查询前添加缺失的空字段:

df$extr_col1 <- NA
df$extr_col2 <- NA
...

然后运行原来的dbWriteTable()

相关内容

最新更新