熊猫to_sql,仅将新行更新到mysql db(主键和重复项)

时间:2018-11-25 07:01:34

标签: python mysql pandas

我在将pd更新到mysql db时遇到问题

for stock_code in cleaned:

    url = 'https://www.hkex.com.hk/chi/sorc/options/statistics_hv_iv_c.aspx?action=csv&type=3&ucode={0}'.format(stock_code)
    df = pd.read_csv(url,index_col='交易日', header=0, skiprows=2)
    df.index.names = ['Trade Date']
    df.index = pd.to_datetime(df.index, dayfirst=True)
    df.insert(loc=0, column ='Stock Code', value=stock_code)
    df.columns = ['Stock Code', 'Implied IV (%)','HV10 (%)','HV30 (%)','HV60 (%)','HV90 (%)']
    df.to_sql(con=database_connection, name='table', if_exists='append')

database_connection.close()

该网址将提供最近3个月的数据:即2018-08-25至2018-11-25, 在今天之后,该网址将提供2018年8月26日至2018年11月26日之间的数据,我想要的是将所有数据保存在db中而无需重复。

我将“交易日期”和“股票代码”设置为主键,但是会产生错误: (mysql.connector.errors.IntegrityError)1062(23000):键'PRIMARY'的条目'2018-11-23-00001'复制了[SQL

如何跳过重复的条目而仅更新新行?非常感谢!

1 个答案:

答案 0 :(得分:0)

据我所知,它没有批量插入(to_sql)的解决方案。您可以尝试以下方法:

for i in range(len(df)):
  try:
      df.iloc[i:i+1].to_sql(name='table', if_exists='append', con=database_connection)
  except IntegrityError:
      pass