pandas dataframe to sql将数据不重复地追加到现有表中

2024-10-01 07:35:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个MySQL表feinstaub,其中有列(created_at,PM 2.5,PM 10,entry_id)c4是唯一的。我有一个pandas数据帧,列名相等。在这个数据帧中是新值和已经存在的值,与sql表相比。我使用这一行将数据帧发送到SQLServer。在

df.to_sql("Feinstaub", con=engine, if_exists="append", index=False)

它只有在数据帧中没有重复的值时才起作用。如果有什么恶作剧。它的价值观是有效的。我找到了这个解决方案:Pandas to_sql() to update unique values in DB?

^{pr2}$

最后我要说的是:

df.to_sql("temp_feinstaub_wohnzimmer", con=engine, if_exists="replace", index=False)
with engine.begin() as cn:
   sql = """INSERT INTO feinstaub (created_at, 'PM 2.5' , 'PM 10', entry_id)
            SELECT t.Column1, t.Column2, t.Column3 ,t.Column4
            FROM temp_feinstaub_wohnzimmer t
            WHERE NOT EXISTS
                (SELECT 1 FROM feinstaub f
                 WHERE t.MatchColumn1 = f.MatchColumn1
                 AND t.MatchColumn2 = f.MatchColumn2
                 AND t.MatchColumn3 = f.MatchColumn3
                 AND t.MatchColumn4 = f.MatchColumn4)"""

   cn.execute(sql)

它引发了一个sql语法错误。我也尝试重命名f.MatchColumn,但还是给了我一个sql语法错误?在

编辑: 我现在使用这个代码,它与反勾一起工作谢谢!但又引起了另一个错误;)

#Send the Data to SQL database
df.to_sql("temp_feinstaub_wohnzimmer", con=engine, if_exists="replace", index=False)
with engine.begin() as cn:
   sql = """INSERT INTO feinstaub (created_at, `PM 2.5` , `PM 10`, entry_id)
            SELECT t.created_at, t.`PM 2.5`, t.`PM 10` ,t.entry_id
            FROM temp_feinstaub_wohnzimmer t
            WHERE NOT EXISTS
                (SELECT 1 FROM feinstaub f
                 WHERE t.created_at = f.created_at
                 AND t.`PM 2.5` = f.`PM 2.5`
                 AND t.`PM 10` = f.`PM 10`
                 AND t.entry_id = f.entry_id)"""

   cn.execute(sql)

现在我得到了以下错误:

sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) (1062, "Duplicate entry '3825' for key 'entry_id'") [SQL: 'INSERT INTO feinstaub_wohnzimmer (created_at, `PM 2.5` , `PM 10`, entry_id)\n            SELECT t.created_at, t.`PM 2.5`, t.`PM 10` ,t.entry_id\n            FROM temp_feinstaub_wohnzimmer t\n            WHERE NOT EXISTS\n                (SELECT 1 FROM feinstaub_wohnzimmer f\n                 WHERE t.created_at = f.created_at\n                 AND t.`PM 2.5` = f.`PM 2.5`\n                 AND t.`PM 10` = f.`PM 10`\n                 AND t.entry_id = f.entry_id)']

Tags: andtofromidsqlwhereselecttemp
1条回答
网友
1楼 · 发布于 2024-10-01 07:35:28

有了这个它对我有用。。。我可以多次执行脚本,只有新值才能进入mysql数据库。在

from sqlalchemy import exc
num_rows = len(df)
#Iterate one row at a time
for i in range(num_rows):
    try:
        #Try inserting the row
        df.iloc[i:i+1].to_sql(name="feinstaub_wohnzimmer",con = engine,if_exists = 'append',index=False)
    except exc.IntegrityError:
        #Ignore duplicates
        pass

相关问题 更多 >