0
点赞
收藏
分享

微信扫一扫

【Python】SQLite3获取新插入的记录ID及ROWID探究

zmhc 2022-05-03 阅读 38

sqlite是一个非常好用的轻量级数据库,并且python自带操作sqlite的函数库,开箱即用,对新手特别友好。

1. 傻瓜式调用

在Python官方API中,sqlite3.Cursor对象有 lastrowid 属性,使用 cursor.lastrowid 即可得到新插入的数据记录的ID值。

翻译:

代码如下:

id = cur.lastrowid

2. 深入研究

仔细看说明,可以发现官方手册中说的是 返回新插入记录的 row id,而不是我们自定义的主键id。

而这个 row id是何方神圣呢?

2.1 row id是什么

也就是说一般的SQLite的每个表都带有 rowid 列。

2.2 rowid table

注意:下文中的 rowid 和 rowid table 都是专有名词,具有特定的含义,指代特定的一类东西。

我们看看 SQLite 官方网站对 rowid table 的介绍,节选翻译自官方网站的此文。

总结一下,就是说:

1. 创建表时,主键要创建为 INTEGER PRIMARY KEY,其实我觉得最好再加上自增 AUTOINCREMENT ,这样最简单最完美。

2. 带有 INTEGER PRIMARY KEY 列的SQLite 数据库表,其 rowid 就是 该INTEGER PRIMARY KEY 列。所以,前面 使用 cur.lastrowid 得到就是我们的ID值了。

3. 创建表SQL语句应该这样:

create table t_haha(id INTEGER PRIMARY KEY AUTOINCREMENT,name text, age INTEGER)

这样这个表 t_haha 的id 列就代表原始的 rowid了。

注意:INTEGER PRIMARY KEY  不要写成了 int primary key。大小写无所谓,但是 integer 不要写成了 int,因为 int 不是 sqlite 的基本数据类型。

3. 代码

# Python3
# -*- coding: utf-8 -*-
import sqlite3

con = sqlite3.connect(":memory:")	# 表示在内存中创建的数据库文件,运行完数据即丢失
cur = con.cursor()
# id 自增
cur.execute("create table t_haha(id INTEGER PRIMARY KEY AUTOINCREMENT,name text, age INTEGER)")

# 第1条数据
data = ("Tom",18)
cur.execute("insert into t_haha(name,age) values (?,?)", data)

# 第2条数据
data = ("Jerry",22)
cur.execute("insert into t_haha(name,age) values (?,?)", data)

# 第3条数据
data = ("Lily",25)
cur.execute("insert into t_haha(name,age) values (?,?)", data)

# 打印全部数据
cur.execute("select * from t_haha")
print(cur.fetchall())
print("===insert 3 data, and last row id is", cur.lastrowid)

# 删除第1条 
cur.execute("delete from t_haha where id = 1")

# 打印全部数据
cur.execute("select * from t_haha")
print(cur.fetchall())
print("===delete the first row")

# 再插入1条数据,此时id自动递增,插入后id应该为4
data = ("Peter",100)
cur.execute("insert into t_haha(name,age) values (?,?)", data)

# 验证下 lastrowid 是否严格和自增的id一致
cur.execute("select * from t_haha")
print(cur.fetchall())
print("===last row id:",cur.lastrowid)

con.close()
con.close()

程序输出如下:

表明 cur.lastrowid 值其实就是我们的 id 列值。

举报

相关推荐

0 条评论