【发布时间】:2021-01-27 18:18:14
【问题描述】:
我正在尝试将新列从 R 附加或 cbind 到 postgresql 表。所以,我在 postgresql 表中创建了一个新列,我想在其中放置我的数据框列,即
ALTER TABLE schema.table
ADD COLUMN newcolumn "char";
library(RPostgres)
library(tidyverse)
library(rpostgis)
# SQL CONNECTION
fun_connect<-function(){dbConnect(RPostgres::Postgres(),dbname = 'mydb',
host = 'localhost', # i.e. 'ec2-54-83-201-96.compute-1.amazonaws.com'
port = 5432, # or any other port specified by your DBA
user = 'postgres',
password = 'secretpass'}
conn <- fun_connect()
mytable<-tbl(conn, "mydb")
# MY data frame
a<-data.frame(a= c("123","231543","1232","45389","4398543"))
# Trying to append or cbind my data frame column
#First try:
copy_to(conn,a,"newcolumn")
#Second try:
RPostgreSQL::dbWriteTable(conn, "table", a,append=T)
So i Have the next error:
Error: COPY returned error: ERROR: el valor nulo en la columna «FIRSTcolumn» de la relación «table» viola la restricción de no nulo
DETAIL: La fila que falla contiene (null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 1).
CONTEXT: COPY table, línea 1: «10208011005»
Third try:
pgInsert(conn, name=c("schema","table"), a)
But I get:
1 out of 1 columns of the data frame match database table columns and will be formatted for database insert.
Error : Failed to fetch row: ERROR: el valor nulo en la columna «FIRSTcolumn» de la relación «table» viola la restricción de no nulo
DETAIL: La fila que falla contiene (null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 1).
Insert failed. No changes made to database.
所以我不知道如何以简单的方式将新列从 R 附加到 Postgresql。我问我是否存在类似于cbind(df, df2) (lol) 的东西,其中 df1 和 df2 具有相同的 nrow,但我都没有代理它是如何可能的
谢谢你的帮助。 问候!
【问题讨论】:
标签: r postgresql dplyr dbplyr rpostgresql