如何使用psycopg2 copy_from在Postgres表中附加数据框

问题描述 投票:0回答:1

我正在尝试将数据框的内容保存在postgres表中。我正在使用这个-

from sqlalchemy import create_engine
import psycopg2 as pg
import io

address = 'postgresql://username:[email protected]:5432/dbname'
engine = create_engine(address)
connection = engine.raw_connection()
cursor = connection.cursor()

df_tbl.reset_index(inplace=True)

command = '''create table data.table_name(
index bigint,
pid varchar,
name varchar);'''
cursor.execute(command)
connection.commit()


output = io.StringIO()

df_tbl.to_csv(output, sep=',', header=False, index=False)

output.seek(0)
contents = output.getvalue()
cur = connection.cursor()

cur.copy_from(output, 'data.table_name', sep=',', null='')
connection.commit()
cur.close()

这将创建表并保存数据。现在,我想继续使用相同的方法将新数据追加到表中。我怎样才能做到这一点?我知道to_sql中有一个if_exists = append函数。但是我不想使用to_sql

使用copy_from将数据追加到postgres的方法是什么?

python postgresql sqlalchemy psycopg2
1个回答
0
投票

Psycopg2提供了两种将内容复制到数据库中的方法:

copy_from()-从类似文件的对象读取数据,并将其附加到数据库表(COPY表FROM文件语法)。源文件必须同时提供read()和readline()方法。

>>> f = StringIO("42\tfoo\n74\tbar\n")
>>> cur.copy_from(f, 'test', columns=('num', 'data'))

copy_expert()-允许处理更多特定情况,并使用PostgreSQL中所有可用的COPY功能。

>>> cur.copy_expert("COPY test TO STDOUT WITH CSV HEADER", sys.stdout)

我不认为您可以直接在Pandas数据帧上使用,但是可以将其转换为StringIO(如果不是太大)或转换为csv(to_csv

© www.soinside.com 2019 - 2024. All rights reserved.