使用 psycopg2 复制到具有 ARRAY INT 列的表

nan*_*nue 5 python postgresql psycopg2 python-3.x pandas

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

create table some_table (
        id serial,
        numbers int []
);
Run Code Online (Sandbox Code Playgroud)

我想以有效的方式复制 pandas 数据帧,所以我不想使用慢速to_sql方法,因此,遵循/sf/answers/2931352371/https://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()
Run Code Online (Sandbox Code Playgroud)

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

所以,我将代码修改为

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()
Run Code Online (Sandbox Code Playgroud)

此代码引发以下错误:

---------------------------------------------------------------------------
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}'"
Run Code Online (Sandbox Code Playgroud)

我应该怎么办 ?

另外,了解为什么第一个代码不会抛出错误将会很有趣。

kli*_*lin 4

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

如果您提交事务,则代码可以正常工作:

cursor.close()
connection.commit()
Run Code Online (Sandbox Code Playgroud)