gpt4 book ai didi

python /sqlite : get PK of newly inserted row

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:11 25 4
gpt4 key购买 nike

我正在使用原始 SQL 插入一行,并且需要获取新插入行的主键。我不能假设任何非 PK 插入数据都是唯一的,也不能假设该行是最后插入的行。

如果无法使用原始 SQL,那么使用“常规”插入怎么样?我在想我将不得不完全创建一个新的 customID 字段。然后我会创建一个随机数变量并将其作为唯一 ID 插入。自从我插入它,我就知道它是什么了。但这似乎违背了将 PK 作为唯一标识符的目的。有没有办法提取序列的下一个 ID(如在 Oracle 中)?

insert_sql = "insert into my_table(title, text) values ('the title', 'the text')"

cursor = connection.cursor()
cursor.execute(insert_sql)
transaction.commit_unless_managed()

最佳答案

... nor can I assume that the row is the last inserted row.

在全局范围内,您不能假设它。但与您的连接相关,您可以 - 因此您可以使用 SELECT LAST_INSERT_ID() 或仅使用 cursor.connection.insert_id()。甚至可能是 cursor.lastrowid,但我不确定它是否也能正常工作。

关于 python /sqlite : get PK of newly inserted row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7737899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com