【问题标题】:Using psycopg2 to COPY to table with an ARRAY INT column使用 psycopg2 复制到带有 ARRAY INT 列的表
【发布时间】:2018-11-27 04:15:27
【问题描述】:

我创建了一个类似于以下结构的表:

create table some_table (
        id serial,
        numbers int []
);

我想以一种有效的方式复制一个 pandas 数据帧,所以我不想使用慢速的to_sql 方法,所以,在https://stackoverflow.com/a/41876462/754176https://stackoverflow.com/a/29125940/754176 之后,我尝试了以下方法:

import pandas as pd
import psycopg2

# Create the connection, and the cursor (ommited)

# Function from the second link
def lst2pgarr(alist):
    return '{' + ','.join(alist) + '}'


df = pd.DataFrame({'numbers': [[1,2,3], [4,5,6], [7,8,9]]})

df['numbers'] = df.numbers.apply(lambda x: lst2pgarr([str(y) for y in x]))

import io
f = io.StringIO()
df.to_csv(f, index=False, header=False, sep="|")
f.seek(0)

cursor.copy_from(f, 'some_table', columns=["numbers"], sep='|')

cursor.close()

此代码不会引发错误,但不会向表中写入任何内容。

所以,我将代码修改为

import csv

df = pd.DataFrame({'numbers': [[1,2,3], [4,5,6], [7,8,9]]})

df['numbers'] = df.numbers.apply(lambda x: lst2pgarr([str(y) for y in x]))


f = io.StringIO()
df.to_csv(f, index=False, header=False, sep="|", quoting=csv.QUOTE_ALL, quotechar="'"))
f.seek(0)

cursor.copy_from(f, 'some_table', columns=["numbers"], sep='|')

cursor.close()

此代码引发以下错误:

---------------------------------------------------------------------------
DataError                                 Traceback (most recent call last)
<ipython-input-40-3c58c4a64abc> in <module>
----> 1 cursor.copy_from(f, 'some_table', columns=["numbers"], sep='|')

DataError: malformed array literal: "'{1,2,3}'"
DETAIL:  Array value must start with "{" or dimension information.
CONTEXT:  COPY some_table, line 1, column numbers: "'{1,2,3}'"

我该怎么办?

另外,知道为什么第一个代码没有抛出错误会很有趣。

【问题讨论】:

  • 将引号字符更改为" 允许我成功使用来自psqlcopy 命令,但我仍然在python 中遇到与上述相同的错误:`DataError:格式错误的数组字面量:""{1,2,3}""`

标签: python python-3.x postgresql pandas psycopg2


【解决方案1】:

此代码不会引发错误,但不会向表中写入任何内容。

如果你提交事务,代码运行良好:

cursor.close()
connection.commit()

【讨论】:

  • 你完全正确!我假设autocommit 已开启
猜你喜欢
  • 1970-01-01
  • 2011-12-29
  • 2013-10-09
  • 2012-01-01
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多