目标
- 打开数据库连接,开始一个事物
- 创建存储对象
- 请求数据库操作:比如添加或查询数据。
- 等待操作完成, 监听正确的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
分享到:
相关推荐
indexeddb-promiseIndexedDB的所有操作都是异步的,API都是在回调函数中执行的,为了便于对其进行操作,使用ES6中的Promise来封装。1. 安装npm包// use npmnpm install --save-dev indexeddb-promise// use yarnyarn...
使用 IndexedDB 和缓存提高性能这是 LinkedIn 学习课程使用 IndexedDB 和缓存提高性能的存储库。 完整课程可从。 随着开发人员努力创建高效工作且可以容忍不可靠网络连接的 Web 应用程序,缓存和本地存储方法变得...
IndexedDB 是一种底层 API,用于在客户端存储大量的结构化数据(也包括文件/二进制大型对象(blobs))。该 API 使用索引实现对数据的高性能搜索。虽然 Web Storage 在存储较少量的数据很有用,但对于存储更大量的...
一个用于React的小型React式IndexedDB绑定。 npm i indexeddb-hooked初始化数据库您将React应用程序与IndexedDBProvider组件连接起来,并在config对象中定义您的模式。 import React from 'react' ;import { ...
IndexedDB简介:浏览器内... 此代码示例演示了如何使用浏览器内部文档数据库IndexedDB来实现持久性。 设置 确保已安装Bower和Gulp: $ npm install -g bower $ npm install -g gulp 然后安装依赖项: $ npm install
IndexedDB 基本使用
使用填充不支持IndexedDB的设备 在Windows设备上使用 在iOS设备上使用 可以选择通过替换设备上的本机IndexedDB 可以选择在设备上增强本机IndexedDB 这个插件基本上是一个IndexedDB-to-WebSql适配器 安装 通过安装...
NuGet安装PM > Install-Package Reshiru.Blazor.IndexedDB.Framework当前功能连接并创建数据库添加记录删除记录编辑记录如何使用在您的startup.cs文件中添加 services . AddSingleton (); IIndexedDbFactory用于创建...
带有承诺的轻量级(gzip压缩)钩子,可在React中轻松访问IndexedDB :anchor: :wrench: 安装 npm i use-indexeddb # npm yarn add use-indexeddb # yarn :books: 故事书 :sparkles: 特征 :leaf_fluttering_in_...
#BabylonJS IndexedDB 后端这个 BabylonJS(2.1 及更高版本)扩展保留添加到特定场景的所有网格。 当网格发生变化时,它也会更新数据库。 除此之外,所有几何图形也保存在不同的数据存储中,并且在用户更新它们时也...
前段时间项目需要本地存储聊天数据,使用到indexedDB,经查阅大量文章,终于完成。感觉网上indexedDB的文章不够多,也不够完善,因此把代码分享出来,帮助需要的小伙伴。
WebSQL到IndexedDB的示例:待办事项列表示例,显示如何将WebSQL转换为IndexedDB
web-worker-indexeddb 使用 Web Worker 访问服务器,并将数据保存在 IndexedDB 中以供离线使用。 在 IndexedDB 中保存数据后,应用程序将始终离线访问数据,并将通过 Web Worker 刷新数据。 使用新的 ES6 标准编写...
这个插件提供了一个围绕 IndexedDB 的薄包装器,可以在您的项目中轻松使用。 目前不支持 Ember 数据。 ** TL:DR 由于 indexeddb 实现的多样性,我不再研究这个库 ** ** 更长的版本,我正在研究这个以在个人项目中...
ngx-indexed-db ngx-indexed-db是一项服务,结合了ngx-indexed-db ,将IndexedDB数据库包装在Angular服务中。安装$ npm install ngx-indexed-db或者$ yarn add ngx-indexed-db用法导入NgxIndexedDBModule并启动它: ...
indexedDB跨平台框架 博文链接:https://appstores.iteye.com/blog/1950529
非常简单的indexedDB例子,自己按照书上面写的, 用的是 visual studio 2012 做的 mvc3 程序。
NULL 博文链接:https://weistar.iteye.com/blog/2186673
使用IndexedDB数据库适配器将共享数据持久存储在浏览器中。 下次您加入会话时,所做的更改仍然存在。 最小化服务器和客户端之间交换的数据量使离线编辑成为可能入门您可以找到在线发布的完整文档: 。 npm i --save...
一个 angularjs 服务提供者,使用带有 angular 的 indexedDB ####Important:这个存储库不再由我维护。 查看当前版本,因为接任成为主要贡献者。 安装 建议使用 Bower 进行安装。 鲍尔 在命令行上调用以下命令: ...