目标
- 打开数据库连接,开始一个事物
- 创建存储对象
- 请求数据库操作:比如添加或查询数据。
- 等待操作完成, 监听正确的DOM事件。
- 对结果进行其它操作。
创建和构建数据存储
使用一个稳定版本的IndexedDB
// In the following line, you should include the prefixes of implementations you want to test.
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
// DON'T use "var indexedDB = ..." if you're not in a function.
// Moreover, you may need references to some window.IDB* objects:
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.")
}
打开数据库
// Let us open our database
var request = window.indexedDB.open("MyTestDatabase");
// open a database with version number
var request = indexedDB.open("MyTestDatabase", 3);
处理机制
var db;
var request = indexedDB.open("MyTestDatabase");
request.onerror = function(event) {
// Do something with request.errorCode!
};
request.onsuccess = function(event) {
// Do something with request.result!
db = request.result;
};
处理错误
db.onerror = function(event) {
// Generic error handler for all errors targeted at this database's
// requests!
alert("Database error: " + event.target.errorCode);
};
创建和更新数据库版本
// This event is only implemented in recent browsers
request.onupgradeneeded = function(event) {
// Update object stores and indices ....
};
构建数据库
IndexedDB 使用对象存储空间而不是表,并且一个单独的数据库可以包含任意数量的对象存储空间。每当一个值被存储进一个对象存储空间时,它会被和一个键相关联。键的提供可以有几种不同的方法,这取决于对象存储空间是使用 key path 还是 key generator。
事务可以接收三种不同类型的 DOM 事件: error,abort,以及 complete。如果在 error 事件上通过调用 preventDefault() 处理了这个错误,整个事务被回滚了。如果在事务中调用 abort(),那么事务被回滚并且有关事物的一个 abort 事件被触发。
// This is what our customer data looks like.
const customerData = [
{ ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
{ ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }
];
const dbName = "the_name";
var request = indexedDB.open(dbName, 2);
request.onerror = function(event) {
// Handle errors.
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create an objectStore to hold information about our customers. We're
// going to use "ssn" as our key path because it's guaranteed to be
// unique.
var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
// Create an index to search customers by name. We may have duplicates
// so we can't use a unique index.
objectStore.createIndex("name", "name", { unique: false });
// Create an index to search customers by email. We want to ensure that
// no two customers have the same email, so use a unique index.
objectStore.createIndex("email", "email", { unique: true });
// Store values in the newly created objectStore.
for (var i in customerData) {
objectStore.add(customerData[i]);
}
};
onupgradeneeded是修改数据结构的唯一方法。
createObjectStore是创建数据对象的方法。例子中可以通过SSN获取存储对象。
添加和删除数据
// adding data
var transaction = db.transaction(["customers"], "readwrite");
transaction.oncomplete = function(event) {
alert("All done!");
};
transaction.onerror = function(event) {
// Don't forget to handle errors!
};
var objectStore = transaction.objectStore("customers");
for (var i in customerData) {
var request = objectStore.add(customerData[i]);
request.onsuccess = function(event) {
// event.target.result == customerData[i].ssn
};
}
// removing data
var request = db.transaction(["customers"], "readwrite")
.objectStore("customers")
.delete("444-44-4444");
request.onsuccess = function(event) {
// It's gone!
};
查询数据
var transaction = db.transaction(["customers"]);
var objectStore = transaction.objectStore("customers");
var request = objectStore.get("444-44-4444");
request.onerror = function(event) {
// Handle errors!
};
request.onsuccess = function(event) {
// Do something with the request.result!
alert("Name for SSN 444-44-4444 is " + request.result.name);
};
使用游标
var objectStore = db.transaction("customers").objectStore("customers");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for SSN " + cursor.key + " is " + cursor.value.name);
cursor.continue();
}
else {
alert("No more entries!");
}
};
// or retriving data and put into the object
var customers = [];
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
customers.push(cursor.value);
cursor.continue();
}
else {
alert("Got all customers: " + customers);
}
};
使用索引
var index = objectStore.index("name");
index.get("Donna").onsuccess = function(event) {
alert("Donna's SSN is " + event.target.result.ssn);
};
// or more complicated...
index.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
// cursor.key is a name, like "Bill", and cursor.value is the whole object.
alert("Name: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email);
cursor.continue();
}
};
index.openKeyCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
// cursor.key is a name, like "Bill", and cursor.value is the SSN.
// No way to directly get the rest of the stored object.
alert("Name: " + cursor.key + ", SSN: " + cursor.value);
cursor.continue();
}
};
设定游标范围和移动方向
// Only match "Donna"
var singleKeyRange = IDBKeyRange.only("Donna");
// Match anything past "Bill", including "Bill"
var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
// Match anything past "Bill", but don't include "Bill"
var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
// Match anything up to, but not including, "Donna"
var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
//Match anything between "Bill" and "Donna", but not including "Donna"
var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);
index.openCursor(boundKeyRange).onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
// Do something with the matches.
cursor.continue();
}
};
// descending...
objectStore.openCursor(null, IDBCursor.prev).onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
// Do something with the entries.
cursor.continue();
}
};
// in the following, IDBCursor.nextunique can also be IDBCursor.prevunique
index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
// Do something with the entries.
cursor.continue();
}
};
当WEB应用在另一个TAB中打开时更改版本
var openReq = mozIndexedDB.open("MyTestDatabase", 2);
openReq.onblocked = function(event) {
// If some other tab is loaded with the database, then it needs to be closed
// before we can proceed.
alert("Please close all other tabs with this site open!");
};
openReq.onupgradeneeded = function(event) {
// All other databases have been closed. Set everything up.
db.createObjectStore(/* ... */);
useDatabase(db);
}
openReq.onsuccess = function(event) {
var db = event.target.result;
useDatabase(db);
return;
}
function useDatabase(db) {
// Make sure to add a handler to be notified if another page requests a version
// change. We must close the database. This allows the other page to upgrade the database.
// If you don't do this then the upgrade won't happen until the user close the tab.
db.onversionchange = function(event) {
db.close();
alert("A new version of this page is ready. Please reload!");
};
// Do stuff with the database.
安全
完整的实例
https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB
分享到:
相关推荐
**使用JsStore在IndexedDB中进行CRUD操作** 在现代Web应用中,处理大量本地数据的需求日益增长。IndexedDB作为浏览器内置的NoSQL数据库,为开发者提供了存储和管理大量结构化数据的能力。而JsStore是一个轻量级的...
- **1000Base-T**:使用更高质量的双绞线或光纤,速率达到1Gbps。 #### 四、网络接口卡(NIC) 网络接口卡是连接计算机与局域网的关键组件,根据其支持的传输速率和技术不同,可以分为多种类型,常见的有ISA和PCI...
2. **IndexedDB**: 这是现代浏览器支持的离线存储标准,用于存储大量复杂数据,包括结构化的JSON对象和二进制数据。IndexedDB提供了键值对存储以及更复杂的索引机制,适合存储和检索大数据量的图片。你可以通过`...
ftdatasquasher 支持数据压缩... 但是,实际上,实际上只使用IndexedDB(当IndexedDB不可用时回退到WebSQL,因为localStorage的容量有限,并且base64编码的二进制文件往往很大。 当存储Web浏览器的脱机存储中的数据(例
- **IndexedDB**:一个非关系型的数据库系统,支持大量复杂数据的本地存储。 6. **Web Workers和Web Socket** - **Web Workers**:在后台运行,处理繁重计算任务,不阻塞用户界面。 - **Web Sockets**:建立持久...
3. **Web Storage & IndexedDB**: 为了存储游戏数据,HTML5提供了Web Storage(包括localStorage和sessionStorage)以及IndexedDB。这些本地存储机制可以帮助游戏保存用户进度、配置信息等,使得游戏体验更加连贯。 ...
4. 学习Web Storage、WebSocket和IndexedDB,了解前端存储和通信技术。 5. 实践HTML5的多媒体功能,如视频和音频的嵌入和控制。 6. 研究Web Workers和Geolocation API,增强应用性能和功能。 总结来说,HTML5不仅...
3. ** localStorage 和 IndexedDB**:HTML5提供了本地存储机制,如localStorage用于简单数据存储,IndexedDB则支持更复杂的数据结构,这两个技术可以用来保存用户的游戏进度、得分等信息,使游戏具有持久化能力。...
2. **Web Storage**或**IndexedDB**:用于在浏览器本地存储游戏数据,如玩家的进度、高分记录等。 3. **事件监听与处理**:如何响应用户的键盘输入、触摸操作来控制游戏角色。 4. **碰撞检测算法**:理解游戏中的...
6. **Web Storage和IndexedDB**:HTML5提供了本地存储机制,如localStorage和sessionStorage,以及更强大的IndexedDB,允许在浏览器中存储大量数据,实现离线应用功能。 7. **WebSocket实时通信**:HTML5的...
3. **Web Storage or IndexedDB**:存储游戏数据,如用户分数、游戏进度。 4. **Web Audio API**:处理游戏音效和背景音乐。 5. **AJAX** 或 **Fetch API**:与服务器进行异步通信,如提交分数、获取排行榜数据。 6....
其中,alasql是一个非常独特且实用的工具,它允许在浏览器或Node.js环境中执行SQL查询,提供对关系数据和嵌套JSON(NoSQL)的支持,同时具备导出到Excel、LocalStorage或IndexedDB的功能。本文将深入探讨alasql的...
3. **Web Storage** 和 **IndexedDB**:这些本地存储机制允许游戏在用户的浏览器中存储数据,如游戏进度、用户设置等,即使在网络断开时也能继续游戏。 4. **WebSocket**:实现双向通信,使实时游戏如多人在线对战...
2. IndexedDB:更强大的数据库存储,适用于大量数据的本地存储。 九、JavaScript库和框架 1. jQuery:简化DOM操作,提供丰富的插件和动画效果。 2. React:Facebook开发的用于构建用户界面的JavaScript库,主打组件...
- 使用Cookies、LocalStorage和IndexedDB的优缺点分析。 6. **实际应用示例** - 在线游戏的进度保存。 - 用户配置和个性化设置的存储。 - 离线Web应用的数据缓存。 由于压缩包文件名称列表只给出了“test”,...
8. **Web Storage和IndexedDB**: HTML5提供了Web Storage(包括localStorage和sessionStorage)和IndexedDB,可以用于存储用户数据和媒体信息,即使在页面刷新或关闭后仍能保留,提高用户体验。 9. **Web Workers...