2 回答

TA貢獻1842條經驗 獲得超22個贊
這是一個關于如何使用 postgres 的ON CONFLICT DO NOTHING示例to_sql
# import postgres specific insert
from sqlalchemy.dialects.postgresql import insert
def to_sql_on_conflict_do_nothing(pd_table, conn, keys, data_iter):
# This is very similar to the default to_sql function in pandas
# Only the conn.execute line is changed
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(insert(pd_table.table).on_conflict_do_nothing(), data)
conn = engine.connect()
df.to_sql("some_table", conn, if_exists="append", index=False, method=to_sql_on_conflict_do_nothing)

TA貢獻1854條經驗 獲得超8個贊
我剛剛遇到了類似的問題,然后對于這個答案,我想出了如何發(fā)送df到的解決方案potgresSQL ON CONFLICT:
1.發(fā)送一些初始數據到數據庫創(chuàng)建表
from sqlalchemy import create_engine
engine = create_engine(connection_string)
df.to_sql(table_name,engine)
2.添加primary key
ALTER TABLE table_name ADD COLUMN id SERIAL PRIMARY KEY;
3. 在要檢查唯一性的列(或列)上準備索引
CREATE UNIQUE INDEX review_id ON test(review_id);
4.映射sql表sqlalchemy
from sqlalchemy.ext.automap import automap_base
ABase = automap_base()
Table = ABase.classes.table_name
Table.__tablename__ = 'table_name'
6. 做你insert on conflict的:
from sqlalchemy.dialects.postgresql import insert
insrt_vals = df.to_dict(orient='records')
insrt_stmnt = insert(Table).values(insrt_vals)
do_nothing_stmt = insrt_stmnt.on_conflict_do_nothing(index_elements=['review_id'])
results = engine.execute(do_nothing_stmt)
添加回答
舉報