码迷,mamicode.com
首页 > 数据库 > 详细

[PWA] 12. Intro to IndexedDB

时间:2016-05-18 06:50:19      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

Use the library indexedDB-promised.

 

Create a database and stroe:

import idb from ‘idb‘;

// Open(db_name, version, cb)
var dbPromise = idb.open(‘test-db‘, 1, function (upgradeDb) {
    var keyValStore = upgradeDb.createObjectStore(‘keyval‘); // create table
    //put(value, key)
    keyValStore.put(‘world‘, ‘Hello‘);
});

Notice put() function take value frist then key.

 

Read the key in stroe:

// read "hello" in "keyval"
dbPromise.then(function (db) {
    var tx = db.transaction(‘keyval‘); // Open a transaction
    var keyValStore = tx.objectStore(‘keyval‘); // read the store
    return keyValStore.get(‘hello‘); // get value by key
}).then(function (val) {
    console.log(‘The value of "hello" is:‘, val);
});

 

Write value to store:

// set "foo" to be "bar" in "keyval"
dbPromise.then(function (db) {
    var tx = db.transaction(‘keyval‘, ‘readwrite‘); // ready for add key value
    var keyValStore = tx.objectStore(‘keyval‘); // get the store
    keyValStore.put(‘bar‘, ‘foo‘); // set the value, notice it may not be success if any step in transaction fail.
    return tx.complete; // tx.complete is a promise
}).then(function () {
    console.log(‘Added foo:bar to keyval‘);
});

 

技术分享

 

[PWA] 12. Intro to IndexedDB

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5503849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!