pandas dataframe to sql-将数据追加到exisitng表而无需重复

时间:2018-12-06 20:55:17

标签: python mysql pandas sqlalchemy

我有一个MySQL表feinstaub,其列(created_at,PM 2.5,PM 10,entry_id)c4是唯一的。而且我有一个具有相同列名的pandas dataFrame。在此数据帧中有新值,并且已经存在的值与sql表进行比较。我使用这一行将数据帧发送到sql server。

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

仅在数据框中没有重复的vlaues时才起作用。如果有的话。重视它确实起作用。我找到了以下解决方案:Pandas to_sql() to update unique values in DB?

with engine.begin() as cn:
   sql = """INSERT INTO myFinalTable (Col1, Col2, Col3, ...)
            SELECT t.Col1, t.Col2, t.Col3, ...
            FROM myTempTable t
            WHERE NOT EXISTS 
                (SELECT 1 FROM myFinalTable f
                 WHERE t.MatchColumn1 = f.MatchColumn1
                 AND t.MatchColumn2 = f.MatchColumn2)"""

   cn.execute(sql)

我最终得到了这个:

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)']

1 个答案:

答案 0 :(得分:0)

它对我有用...我可以多次执行该脚本,只有新值才能进入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