首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从R的dataframe向postgresql表追加新列

问如何从R的dataframe向postgresql表追加新列
EN

Stack Overflow用户
提问于 2021-01-28 02:18:15
回答 1查看 264关注 0票数 0

我正在尝试将R中的新列附加或cbind到postgresql表中。因此,我在postgresql表中创建了一个新列,用于放置我的数据框列,即

代码语言:javascript
复制
ALTER TABLE schema.table
    ADD COLUMN newcolumn "char";
代码语言:javascript
复制
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,但我也没有一个代理来说明它是如何实现的

谢谢你的帮助。致以问候!

EN

回答 1

Stack Overflow用户

发布于 2021-01-28 06:55:04

首先,您有两种不同类型的数据对象。一个是到远程(不在R内存中) sql表的连接,另一个是本地(在R内存中)数据帧。这两种类型的对象不能立即合并。这意味着这些数据类型没有简单的cbind等效项。

我建议首先将本地数据帧复制到sql数据库中。然后,您将拥有两个可以组合的相同类型的数据对象--两个sql表。

您尝试使用copy_to和dbWriteTable是一个很好的开始。但是这些函数将整个R数据帧写入整个表中,而不是作为表的一部分。

为了将数据帧复制到sql中,我使用:

代码语言:javascript
复制
DBI::dbWriteTable(
      db_connection,
      DBI::Id(
        catalog = db,
        schema = schema,
        table = sql_table_name
      ),
      r_table_name
)

您正在寻找的用于插入值的sql语法很可能是:

代码语言:javascript
复制
INSERT INTO first_table(names_of_columns1) SELECT names_of_columns2 FROM second_table;

我会在R中使用类似下面的代码:

代码语言:javascript
复制
insert_into_column <- function(connection, tbl1, col1, tbl2, col2){
    prep = tbl2 %>% select(col2)

    query <- glue::glue("INSERT INTO {tbl1} ({col1})\n",
                        dbplyr::sql_render(prep))

    result <- DBI::dbExecute(connection, as.character(query))
}

请注意,向sql表的列插入值可能与向R数据帧的列插入值的工作方式不同。缺省情况下,sql中的表不排序,因此插入操作可能无法保证正确的顺序。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65925021

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档