indexeddb 中可通过设置 keypath 并启用 autoincrement 实现主键自增:创建 objectstore 时指定 keypath(如"id")并设 autoincrement: true,插入时省略或设 id 为 undefined,系统自动生成递增数字 id。

IndexedDB 中无法像 SQL 数据库那样直接设置主键自增(AUTO_INCREMENT),但可以通过 autoIncrement 选项配合不指定 key 的方式,实现“主键自增”的效果。关键在于:**对象存储(objectStore)创建时启用 autoIncrement,并且插入时不传入 key(或传 undefined)**,系统会自动分配递增的数字主键。
创建支持自增主键的对象存储
在数据库升级(onupgradeneeded)中定义 objectStore 时,将 keyPath 设为一个属性名(如 "id")并开启 autoIncrement:
// 打开或升级数据库
const request = indexedDB.open("myDB", 2);
request.onupgradeneeded = event => {
const db = event.target.result;
// 删除旧 store(可选)
if (db.objectStoreNames.contains("users")) {
db.deleteObjectStore("users");
}
// 创建新 store:keyPath 为 "id",autoIncrement 为 true
const store = db.createObjectStore("users", {
keyPath: "id",
autoIncrement: true
});
// 可选:添加索引
store.createIndex("name", "name", { unique: false });
};
此时,每条记录的 id 字段将由 IndexedDB 自动填充(从 1 开始,每次 +1),你无需手动赋值。
插入新记录时省略 key 或设为 undefined
调用 add() 方法时,**不要给对象提供 id 属性,或显式设为 undefined/null**,否则会覆盖 autoIncrement 行为:
- ✅ 正确(自动生成 id):
store.add({ name: "Alice", email: "a@example.com" }) - ✅ 正确(显式忽略):
store.add({ name: "Bob", email: "b@example.com", id: undefined }) - ❌ 错误(手动指定 id):
store.add({ id: 100, name: "Charlie", email: "c@example.com" })—— 这会强制使用 100,破坏自增序列
注意:如果 keyPath 是字符串(如 "id"),则不能用 put() 并传入外部 key,否则会报错(违反 keyPath 约束)。想用 put 且保持自增,应传入完整对象,不带 keyPath 字段。
读取时确认自增 ID 已生成
add 操作成功后,可通过事务的 oncomplete 或 Promise 获取生成的 key(即自增 id):
const transaction = db.transaction(["users"], "readwrite");
const store = transaction.objectStore("users");
const addRequest = store.add({ name: "David", email: "d@example.com" });
addRequest.onsuccess = () => {
console.log("新记录 ID:", addRequest.result); // 输出自增的数字,如 4
};
// 或用 Promise 封装(现代写法)
function addRecord(store, data) {
return new Promise((resolve, reject) => {
const req = store.add(data);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
// 使用
addRecord(store, { name: "Eve", email: "e@example.com" })
.then(id => console.log("插入成功,ID =", id));
常见误区与注意事项
-
autoIncrement 只对 keyPath 有效:如果 keyPath 是
null或未设置,autoIncrement 无效;必须明确指定 keyPath 字符串(如 "id") - 自增 ID 是全局连续但不绝对可靠:若插入失败、事务回滚或数据库被删除重建,ID 可能跳号;它不保证严格连续,只保证递增且唯一
-
不能修改已存在的 keyPath 字段:一旦数据写入,id 字段不可更改(因为它是主键);如需更新,用
put()替换整个对象 - 避免混合使用手动 ID 和 autoIncrement:同一 store 中混用会导致 key 冲突或意外覆盖
不复杂但容易忽略细节:核心就是创建时声明 keyPath + autoIncrement,插入时“什么都不给 ID”,让浏览器代劳。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











