【问题标题】:sqlite3 error UNIQUE constraint failed: tablename.idsqlite3 错误唯一约束失败:tablename.id
【发布时间】:2021-10-25 01:34:20
【问题描述】:

我让这个 sqlite3 代码在程序主体中完美运行,我认为就是这样,但后来我编写了更多代码,因此它将每月执行一次(在每月的第一天(这就是它坏掉的原因。

我已经搜索了半天并查看了唯一键等等,但似乎问题是表名抛出了一个 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()

【问题讨论】:

  • 将错误的完整回溯显示为问题中格式正确的文本。
  • 投诉与表名无关。您的表定义有 id 作为主键。这意味着它不能被复制。您的代码始终以 id=1 开头。如果id 1 已经存在,那就是UNIQUE 约束失败。您的意思是在开始之前删除所有行吗?
  • 对不起,我没有对错误进行属性格式化,但这实际上是整个错误消息,只是一个简单的行:“sqlite3 error UNIQUE constraint failed: currentMonthStocks.id”
  • 现在表完全是空的,所以我不知道如何删除不存在的行。但它是一个好主意,如何编写一个语句来删除所有,或删除行,或重置为空?
  • Tim Roberts,这很有帮助,我从它起作用的插入语句中删除了 id ......有点。代码运行并且不会引发错误,但它仍然没有使用条目填充数据库。在打印语句之间,并且在将代码移动到函数之前肯定会正确运行,我仍然很困惑,但是感谢您提供关于省略 ID 列的提示,因为它会自动递增。

标签: python python-3.x sqlite python-sql


【解决方案1】:

上面提到了正确的答案,我需要在输入新行之前删除所有行。这个问题比它需要的要严重得多,因为我用来查看条目的应用程序 SQLite 的 DB Browser 有某种内部错误,我不得不重新启动计算机,然后结果证明我基本上正确地编写了代码。这最终成为正确的工作代码:

        if c.execute("""SELECT EXISTS(SELECT 1 FROM currentMonthStocks WHERE id=1 LIMIT 2);"""):
        # for i in range(len(this_months_symbols)):
        c.execute("""DELETE FROM currentMonthStocks""")
        print("delete all rows successful")

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2021-10-06
    相关资源
    最近更新 更多