python - 使用Python在SQLite中插入行后如何检索插入的ID?

使用 Python 在 SQLite 中插入行后如何检索插入的 id?我有这样的表:

id INT AUTOINCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50)

我用示例数据 username="test"password="test" 插入一个新行。如何以事务安全的方式检索生成的 id?这适用于网站解决方案,其中两个人可能同时插入数据。我知道我可以获得最后读取的行,但我认为这不是事务安全的。有人可以给我一些建议吗?

最佳答案

您可以使用 cursor.lastrowid (参见“可选 DB API 扩展”):

connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('test','test'))
print(cursor.lastrowid)
# 1

如果两个人同时插入,只要使用不同的cursorcursor.lastrowid都会返回id cursor 插入的最后一行:

cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

print(cursor2.lastrowid)        
# 3
print(cursor.lastrowid)
# 2

cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
               (100,'blah','blah'))
print(cursor.lastrowid)
# 100

请注意,当您使用 executemany 一次插入多行时,lastrowid 返回 None:

cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
               (('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None

https://stackoverflow.com/questions/6242756/

相关文章:

linux - 使用 find 命令但排除两个目录中的文件

python - 未找到 Virtualenv 命令

python - 在 Python 中使用多个参数进行字符串格式化(例如 '%s ... %s' )

linux - 使用 bash 为文件添加文件扩展名

linux - 选择 Linux I/O 调度程序

python - 如何在python中打印百分比值?

python - ConfigParser 中的列表

python - 仅在 Django 启动 ONCE 时执行代码?

ruby - 找不到 gem 命令

linux - 仅使用 shell 脚本从文本文件中获取特定行