pandas到\u sql,只将新行更新到mysql数据库(主键和复制)

2024-04-25 04:59:53 发布

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

我在更新pd到mysql数据库时遇到问题

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()

url将提供最近3个月的数据:即2018-08-25至2018-11-25, 今天之后,url会给2018-08-26到2018-11-26的数据,我想要的是把所有的数据都保存在db中而不重复。在

但将主键设置为“交易代码”时出错(&T): (mysql.connector.errors.IntegrityError)1062(23000):键“PRIMARY”的重复条目“2018-11-23-00001”[SQL

如何跳过重复项而只更新新行?谢谢!在


Tags: csvto数据数据库urldfindexstock
1条回答
网友
1楼 · 发布于 2024-04-25 04:59:53

据我所知,它没有大容量插入的解决方案(到\u 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

相关问题 更多 >