如何在使用Python在SQLite中插入行后检索插入的id?我有这样的表:
id INT AUTOINCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50)
Run Code Online (Sandbox Code Playgroud)
我插入一个新行,例如数据username="test"
和password="test"
.如何以事务安全的方式检索生成的id?这适用于网站解决方案,其中两个人可能同时插入数据.我知道我可以得到最后一行,但我不认为这是交易安全的.有人可以给我一些建议吗?
unu*_*tbu 232
您可以使用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
Run Code Online (Sandbox Code Playgroud)
如果两个人同时插入,只要他们使用不同的cursor
s,cursor.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
Run Code Online (Sandbox Code Playgroud)
请注意,当您一次插入多行时lastrowid
返回:None
executemany
cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
(('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None
Run Code Online (Sandbox Code Playgroud)
Ste*_*ker 15
@Martijn Pieters在评论中的所有功劳:
您可以使用该功能last_insert_rowid()
:
该
last_insert_rowid()
函数ROWID
从调用该函数的数据库连接返回最后一行插入的 。的last_insert_rowid()
SQL函数是围绕一个包装sqlite3_last_insert_rowid()
C / C ++接口功能。
RETURNING
在SQLite 3.35 中使用:create table users (
id integer primary key,
first_name text,
last_name text
);
insert into users (first_name, last_name)
values ('Jane', 'Doe')
returning id;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
99451 次 |
最近记录: |