pandas to_sql在重复的主键上失败 [英] Pandas to_sql fails on duplicate primary key

查看:826
本文介绍了 pandas to_sql在重复的主键上失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用pandas df.to_sql()函数追加到现有表中.

I'd like to append to an existing table, using pandas df.to_sql() function.

我设置了if_exists='append',但是我的表有主键.

I set if_exists='append', but my table has primary keys.

在尝试对现有表进行append时,我想做与insert ignore等效的操作,因此我将避免重复的输入错误.

I'd like to do the equivalent of insert ignore when trying to append to the existing table, so I would avoid a duplicate entry error.

大熊猫有可能吗?还是我需要写一个明确的查询?

Is this possible with pandas, or do I need to write an explicit query?

推荐答案

很遗憾,没有选项可以指定"INSERT IGNORE".这就是我克服的限制,可以在数据库中插入不重复的行(数据帧名称为df)

There is unfortunately no option to specify "INSERT IGNORE". This is how I got around that limitation to insert rows into that database that were not duplicates (dataframe name is df)

for i in range(len(df)):
    try:
        df.iloc[i:i+1].to_sql(name="Table_Name",if_exists='append',con = Engine)
    except IntegrityError:
        pass #or any other action

这篇关于 pandas to_sql在重复的主键上失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆