Python 使用psycopg2复制到具有数组INT列的表
我创建了一个具有如下结构的表:Python 使用psycopg2复制到具有数组INT列的表,python,python-3.x,postgresql,pandas,psycopg2,Python,Python 3.x,Postgresql,Pandas,Psycopg2,我创建了一个具有如下结构的表: create table some_table ( id serial, numbers int [] ); import pandas as pd import psycopg2 # Create the connection, and the cursor (ommited) # Function from the second link def lst2pgarr(alist): return '{' + ','
create table some_table (
id serial,
numbers int []
);
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()
我想以一种高效的方式复制熊猫数据帧,因此我不想使用慢速to_sql
方法,因此,我尝试了以下方法:
create table some_table (
id serial,
numbers int []
);
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}'"
---------------------------------------------------------------------------
数据错误回溯(最近一次呼叫上次)
在里面
---->1游标。从(f,‘某些表格’,列=[“数字”],sep='|')复制
DataError:数组文字格式错误:“{1,2,3}”
详细信息:数组值必须以“{”或维度信息开头。
上下文:复制一些_表,第1行,列号:“{1,2,3}”
我该怎么办
另外,了解第一个代码为什么不抛出错误也很有趣
这段代码不会抛出错误,但不会向表中写入任何内容
如果您提交事务,则代码运行良好:
cursor.close()
connection.commit()
将引号字符更改为
“
允许我成功地使用psql
中的copy
命令,但我仍然在python
中遇到与上面相同的错误:`DataError:marroformed array literal:“{1,2,3}”`你完全正确!我假设autocommit
处于启用状态