我正在尝试将数据框的内容保存在postgres表中。我正在使用-
from sqlalchemy import create_engine
import psycopg2 as pg
import io
address = 'postgresql://username:password@dbname.endpoint.rds.amazonaws.com: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的方法是什么?