如何在使用 while 循环从 python 导出时覆盖 SQL 行的数据?

How do I overwrite the data on SQL rows while exporting from python using while loop?

我正在尝试制作每分钟刷新一次的实时股票报价 Microsoft Excel 电子表格。我尝试的是在 python 中创建一个数据框,然后将其导出到 SQL,然后从 excel 到 SQL table 的数据连接,因为 [=13] =] 在 Excel 文件打开时不起作用,我需要打开该文件。我创建了一个 while 循环(忽略分钟变量的值,因为它是随机的)和 df.to_sql 在里面。问题在于,循环不会覆盖数据,而是在每次执行时创建新行。如何覆盖相同现有行中的数据?我的代码如下:

import yfinance as yf
import pandas as pd
from sqlalchemy import create_engine
import urllib


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


scrip = ['BLUESTARCO', 'AARTIIND', 'LUPIN','MFSL']
data = []
minutes = 0
while minutes < 340:
    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'])
    quoted = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=SHRICOH;DATABASE=PythonImportTesting")
    engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted))
    df.to_sql('Live Ticker Yfinance', schema='dbo', con=engine,
          chunksize=200, method='multi', index=False, if_exists='replace')
    minutes += 1

SQL 中的 table 就是这样更新的。 [1]: https://i.stack.imgur.com/lPPjl.png

在您的代码中,您永远不会在获取新项目后重置 data 列表,因此您仍然拥有旧数据,这就是您存储在 SQL 数据库中的数据。 解决方法是简单地将数据重置为 while 循环中的空列表

scrip = ['BLUESTARCO', 'AARTIIND', 'LUPIN','MFSL']
# Instead of here
minutes = 0
while minutes < 340:
    # Declare data here
    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'])
    quoted = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=SHRICOH;DATABASE=PythonImportTesting")
    engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted))
    df.to_sql('Live Ticker Yfinance', schema='dbo', con=engine,
          chunksize=200, method='multi', index=False, if_exists='replace')
    minutes += 1