【问题标题】:inserting dataframe to mysql table efficiently有效地将数据框插入mysql表
【发布时间】:2023-01-26 06:44:35
【问题描述】:

我想将 df 插入到 mysql 表中,但我想比现在快得多,因为它非常慢。这是我的代码。

            for i in range(len(mydf)):
            try:
                mydf.iloc[i:i+1].to_sql(save_table, con=my_engine, schema='my_schema', index=False, if_exists='append')
            except exc.IntegrityError as e:
                pass
            except Exception as e:
                logging.error("General exception was passed. Error was {}".format(e))
                pass

我以前的方法是这样做的,但是如果表已经有该行,它将在重复的行上无限循环。因为它会开始使用这个过程。

try:
   mydf.to_sql(save_table, con=engine, index=False, if_exists='append')
except exc.IntegrityError as e:
   logging.info("Bypassing duplicates")
except Exception as e:
   logging.info("General exception was passed. Error was {}".format(e))

想知道我是否应该将我的 df 转换为列表并以这种方式循环遍历它,或者有更好的方法吗?

【问题讨论】:

    标签: python mysql dataframe


    【解决方案1】:

    这似乎是最快的事情。

    list_values = [tuple(r) for r in self.main_sdn.to_numpy().tolist()]
    try:
       cur.executemany(query_string, list_values)
       con.commit()
    except exc.IntegrityError as e: 
       pass
    except Exception as e:
       con.rollback()
       logging.error("Exception was {}".format(e))
       con.close()
    

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 2022-11-11
      • 2012-05-10
      • 1970-01-01
      • 2013-02-20
      • 2015-01-09
      • 2012-10-01
      • 2016-02-03
      相关资源
      最近更新 更多