持久性:IndexedDB==WEB SQL DB> Local storage>session storage
注:IndexedDB和WEB SQL DB的区别主要在于 IndexedDB是NoSQL的WEB数据库,而WEB SQL DB是SQL数据库
当你在chrome下 F12--->Resources选项卡中如下东西
session storage的用法 作用域:当前选项卡页面
sessionStorage.setItem(key,value);//插入数据
sessionStorage.removeItem(key);//删除数据
sessionStorage.getItem(key);//获取数据
local storage的用法 作用域:当前不关闭的浏览器,多个选项卡之间可以传递值
localStorage.setItem(key,value);//插入数据
localStorage.removeItem(key);//删除数据
localStorage.getItem(key);//获取数据
web sql db 用法 作用域:整个浏览器,清除缓存不影响,除非调用 sql的 delete方法。使用方法如下:
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
msg = 'Log message created and row inserted.';
console.log(msg);
});
<pre name="code" class="javascript"> db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "Found rows: " + len ;
console.log(msg)
for (i = 0; i < len; i++){
msg = "row:" + results.rows.item(i).log ;
console.log(msg);
}
}, null);
});
indexeddb 用法 作用域:整个浏览器,清除缓存不影响,除非调用delete
方法。使用方法如下:
var request=window.indexedDB.open("TestDB",1);request.οnerrοr=function(e){ console.log(e.currentTarget.error.message); }; request.onsuccess=function(e){ myDB.db=e.target.result; }; request.onupgradeneeded=function(e){ var db=e.target.result; if(!db.objectStoreNames.contains('students')){ db.createObjectStore('students',{autoIncrement: true}); } console.log('DB version changed to '+version); };var datas=[{ id:001, name:"zhangsan" },{ id:002, name:"lisi" },{ id:003, name:"wangwu" }];var transaction=db.transaction(storeName,'readwrite'); var store=transaction.objectStore(storeName); for(var i=0;i<students.length;i++){ store.add(datas[i]); }