10
09/2014
html5 本地存储
Chrome 支持
- Cookies
- Local Storage
- Session Strorage
- Web SQL
- IndexedDB
Local Storage
浏览器都支持,简单的 key:value,不能查询,大小 5M。
检查是否支持
window.localStorage
设值
localStorage.setItem(‘name’,’guoshuang’)
或者 localStorage.[‘name’]=’guoshuang’)
取值
localStorage.getItem(‘name’)
或者 localStorage[‘name’]
删除
localStorage.removeItem(‘name’)
for
遍历
for(var i=0; i< localStorage.length;i++){ var key = localStorage.key(i); console.log(key + ":" + localStorage[key]); }
Web SQL
建库、建表、插值
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")');
执行查询
db.transaction(function (tx) { tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { var len = results.rows.length, i; msg = "<p>Found rows: " + len + "</p>"; document.querySelector('#status').innerHTML += msg; for (i = 0; i < len; i++){ msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; document.querySelector('#status').innerHTML += msg; } }, null); });
中间的参数 argument intended to allow variables to be substituted into statements without risking SQL injection vulnerabilities 是为了安全!
db.readTransaction(function (t) { t.executeSql('SELECT title, author FROM docs WHERE id=?', [id], function (t, data) { report(data.rows[0].title, data.rows[0].author); }); });
删除表
var db = openDatabase("数据库名",'2.0',"描述",60*60*60); db.transaction(function(tx){ //drop table tx.executeSql("drop table 表名"); })
检查是否已经存在表,避免重复
SELECT name FROM sqlite_master WHERE type=”table” AND name=”t_app_auditcims”
参考资料: http://www.w3.org/TR/webdatabase/
indexedDB
平面数据库 key/value 加简单索引
window.indexedDB.open("CandyDB","My candy store database");
Session Strorage
和 localStorage 几乎一样。区别,window.sessionStorage 重启浏览器就没了。