I have a SQL Server database table which contains stock market OHLC data loading from CSV file. I am live data into CSV so every specific interval, one row gets added in CSV file, same I need to add in database table. This database needs to be updated at regular interval, say 1 minute.
def printit():
threading.Timer(60, printit).start()
data_1_min = pd.DataFrame(mt.copy_rates_range("EURUSD.", mt.TIMEFRAME_M1, datetime.datetime(2022, 1, 1), dt.now()))
data_1_min.drop(['tick_volume', 'spread'], axis = 1, inplace = True)
data_1_min['time'] = [dt.fromtimestamp(x).strftime("%m-%d-%Y %H:%M:%S") for x in data_1_min['time']]
data_1_min['TF'] = '1M'
data_1_min.rename(columns = {'time':'Time','open':'O', 'high':'H','low':'L', 'close':'C', 'real_volume':'V'}, inplace = True)
data_file = data_1_min.to_csv('data1.csv', index = False)
with open ('data1.csv', 'r') as f:
reader = csv.reader(f)
columns = next(reader)
query = 'insert into mytable({0}) values ({1})'
query = query.format(','.join(columns), ','.join('?' * len(columns)))
cursor = cnxn.cursor()
for data in reader:
cursor.execute(query, data)
cursor.commit()
printit()
Whenever I refresh database table, it loads all rows from CSV file, not only new rows. Tried with if not exists and merge but it taking long time. Want solution to save these live data to database. Using Microsoft SQL server management Studio 18. Doing all code in Python.