IndexDB

由于网上很难找到完整的demo,自己写了一个以后,放在这里,留着以后学习使用:

var databaseName = 'databaseName1';

    var version = '23';

    var request = window.indexedDB.open(databaseName, version);

    console.log('request', request);

    request.onerror = function (event) {

        console.log('数据库打开报错');

    };

    var db;

    request.onsuccess = function (event) {

        db = request.result;

        console.log('数据库打开成功');

        add();

    };

    request.onupgradeneeded = function(event) {

        db = event.target.result;

        var objectStore = db.createObjectStore('person', { keyPath: 'id' });

        objectStore.createIndex('name', 'name', { unique: false });

        objectStore.createIndex('email', 'email', { unique: true });

    };

    function add() {

        var request = db.transaction(['person'], 'readwrite')

            .objectStore('person')

            .add({ id: 1, name: '张三', age: 24, email: '[email protected]' });

        request.onsuccess = function (event) {

            console.log('数据写入成功');

            read();

        };

        request.onerror = function (event) {

            console.log('数据写入失败');

        }

    }

    function read() {

        var transaction = db.transaction(['person']);

        var objectStore = transaction.objectStore('person');

        var request = objectStore.get(1);

        request.onerror = function(event) {

            console.log('事务失败');

        };

        request.onsuccess = function( event) {

            if (request.result) {

                console.log('Name: ' + request.result.name);

                console.log('Age: ' + request.result.age);

                console.log('Email: ' + request.result.email);

            } else {

                console.log('未获得数据记录');

            }

        };

    }

你可能感兴趣的:(IndexDB)