我让这个 sqlite3 代码在程序主体中完美运行,我认为就是这样,但后来我编写了更多代码,因此它将每月执行一次(在每月的第一天),然后代码工作正常,但是现在当表格条目出现时,sqlite3 error UNIQUE constraint failed: currentMonthStocks.id
我确实将代码从主体移动到函数中,当时我在底部编写每月调用,我不确定这是否是这个问题的原因.
我已经搜索了半天并查看了唯一键等等,但似乎问题是表名抛出了一个 UNIQUE 约束错误,这很奇怪,因为表存在,并且只有1 个具有该名称的表。所有其他代码都应该可以正常工作。我试图将 INSERT INTO 更改为 INSERT 或 IGNORE INTO 并且 for 循环运行,但没有插入任何内容。我仔细检查了一下,桌子是空的。
def get_symbols_at_month_start() -> None:
"""Function inserts a list of symbols to trade every month into the currentMonthStocks table in database.db.
This is called once at the start of the month, deletes the current symbols and adds the new ones.
:return: None."""
print('running get symbols function')
# curl for marketsmith stocks:
url = "https://marketsmith.investors.com/mstool/api/tool/list-table"
payload = "{...}"
headers = {...}
response = requests.request("POST", url, headers=headers, data=payload)
symbols = response.json()['content']['allInstrumentRows']
this_months_symbols = []
for symbol in symbols:
this_months_symbols.append(symbol['Symbol'])
# DATABASE
try:
conn = sqlite3.connect('database.db')
c = conn.cursor()
print("Database Connected")
# c.execute("""CREATE TABLE currentMonthStocks (
# id INT PRIMARY KEY,
# symbol TEXT,
# month INT)""")
# print("DB created successfully")
time_now = datetime.datetime.now() # get current time for the int conversion below
this_month_int = time_now.month # get the current month and set it to an int
db_row_id = 1 # set the first row number
for i in range(len(this_months_symbols)):
c.execute("""INSERT INTO currentMonthStocks
(id, symbol, month)
VALUES (?, ?, ?)""", (db_row_id, this_months_symbols[i], this_month_int))
db_row_id += 1
print("one more entry")
print("symbols successfully populated into db")
conn.commit() # commits the current transaction.
# c.close() # closes the connection to the db.
except sqlite3.Error as e:
print("sqlite3 error", e)
finally:
if conn:
conn.close()
print("Database Closed")
# set the timing of the get_symbols_at_month_start() code
today = datetime.datetime.now()
nextMonth = (today.replace(day=1) + datetime.timedelta(days=32)).replace(day=1) # get first day of next month
diffMins = ((nextMonth - today).total_seconds()) / 60.0 # get difference in minutes
scheduler = BackgroundScheduler()
# scheduler.add_job(func=get_symbols_at_month_start, trigger='interval', minutes=diffMins)
scheduler.add_job(func=get_symbols_at_month_start, trigger='interval', seconds=8)
scheduler.start()