You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用while循环导出数据到SQL时如何覆盖原有行数据

问题根因

你遇到的每次写入SQL都会新增行的核心问题是data列表定义在while循环外部,每次循环执行都会往列表里追加新的股票数据,导致生成的df本身就包含了本次+之前所有循环的历史数据,哪怕用了if_exists='replace'参数,也是把整张表替换成了包含历史数据的更长的df,视觉上就像不断新增行。

修正后代码

import yfinance as yf
import pandas as pd
from sqlalchemy import create_engine
import urllib
import time # 用于控制每分钟执行一次

def get_current_price(symbol):
    ticker = yf.Ticker(symbol)
    todays_data = ticker.history(period='1d')
    return todays_data['Close'][0]

# 数据库连接初始化放到循环外,避免重复创建浪费资源
quoted = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=SHRICOH;DATABASE=PythonImportTesting")
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted))

scrip = ['BLUESTARCO', 'AARTIIND', 'LUPIN','MFSL']
minutes = 0
while minutes < 340:
    # data列表放到循环内部,每次循环清空重新采集最新数据
    data = []
    for x in scrip:
        y = x
        x = x + '.NS'
        price = ('%.6s' % get_current_price(x))
        final = [y, price]
        data.append(final)
    df = pd.DataFrame(data, columns=('symbol', 'CMP'))
    print(df['CMP'])
    df.to_sql('Live Ticker Yfinance', schema='dbo', con=engine,
          chunksize=200, method='multi', index=False, if_exists='replace')
    minutes += 1
    # 等待60秒后执行下一次刷新,符合每分钟更新的需求
    time.sleep(60)

改动说明

  • 核心修改:将data = []移到while循环内部,每次循环只保留当前最新的4只股票报价数据,生成的df永远只有4行,调用to_sql设置if_exists='replace'就会直接覆盖整张表为最新数据,不会保留历史行
  • 优化项:将数据库引擎创建逻辑移到循环外部,避免每次循环重复创建连接,降低性能损耗
  • 补充:新增time.sleep(60)控制刷新频率,匹配你每分钟自动刷新的需求,不需要可以直接删除

内容的提问来源于stack exchange,提问作者Shrinidhi Shetty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:27:03