使用to_sql更新记录

时间:2018-11-24 12:37:06

标签: python pandas

我正在尝试使用Pandas将文本文件中的df与sql数据库中的df进行比较。如果文本文件df中的某个项目不同,我希望插入,或者如果数据库中已有该项目,请更新该字段。

# Text File
# "Id","Stock_ID","Colour"
# "298","203","Green"

df1 = pd.read_table("data.txt", sep = ",")
df2 = pd.read_sql_table("mytable", con=engine)


df3 = pd.concat([df2, df1], sort=False).drop_duplicates(subset = . 
["Stock_ID"], keep=False)
df4 = df3.loc[pd.isnull(df3.id)] # This contains the new record to update

df4.to_sql('feed', con=engine, if_exists='replace', index_label='id', 
dtype={
    'id': sqlalchemy.INTEGER(), 
})

df4.to_sql引发错误ValueError: duplicate name in index/columns: cannot insert id, already exists

如何通过ID更新数据库中的行?

0 个答案:

没有答案