前端存储数据库----IndexedDB

前端需要存储结构化大数据时;就需要用到前端数据库的存储方式( Web SQL、IndexedDB);这里我们了解下IndexedDB

简述

IndexedDB是一种底层API,用于客户端存储大量结构化数据(包括, 文件/ 二进制大型对象(blobs)。

IndexedDB是一个事务型数据库系统,类似于基于SQL的RDBMS。 然而,不像RDBMS使用固定列表,IndexedDB是一个基于JavaScript的面向对象数据库。

IndexedDB允许您存储和检索用键索引的对象;可以存储结构化克隆算法支持的任何对象。

特点

(1)键值对储存。 IndexedDB 内部采用对象仓库(object store)存放数据。所有类型的数据都可以直接存入,包括 JavaScript 对象。对象仓库中,数据以"键值对"的形式保存,每一个数据记录都有对应的主键,主键是独一无二的,不能有重复,否则会抛出一个错误。

(2)异步。 IndexedDB 操作时不会锁死浏览器,用户依然可以进行其他操作,这与 LocalStorage 形成对比,后者的操作是同步的。异步设计是为了防止大量数据的读写,拖慢网页的表现。

(3)支持事务。 IndexedDB 支持事务(transaction),这意味着一系列操作步骤之中,只要有一步失败,整个事务就都取消,数据库回滚到事务发生之前的状态,不存在只改写一部分数据的情况。

(4)同源限制 IndexedDB 受到同源限制,每一个数据库对应创建它的域名。网页只能访问自身域名下的数据库,而不能访问跨域的数据库。

(5)储存空间大 IndexedDB 的储存空间比 LocalStorage 大得多,一般来说不少于 250MB,甚至没有上限。

(6)支持二进制储存。 IndexedDB 不仅可以储存字符串,还可以储存二进制数据(ArrayBuffer 对象和 Blob 对象)。

操作

1.连接数据库

/**
 * 打开数据库,数据库不存在则默认新建
 * name  数据库名
 * version  版本号,没有则默认当前版本
*/
var indexDb = window.indexedDB.open('ceshi', 1); 

2.会触发的事件监听

var db
/**
 * 事件监听
 * error  失败
*/
indexDb.onerror = function(event){
    console.log('数据库打开失败')
}

/**
 * 事件监听
 * success 成功
*/
indexDb.onsuccess = function(event){
    db = indexDb.result
    console.log('数据库打开成功')
}

/**
 * 事件监听
 * upgradeneeded 版本升级;新建数据库从无到有可以触发该监听
*/
indexDb.onupgradeneeded = function(event){
    db = event.target.result;
}

3.新建对象仓库(建立索引)

indexDb.onupgradeneeded = function(event){
    db = event.target.result;
    var objectStore;
    // 判断是否存在对象仓库
    if (!db.objectStoreNames.contains('person')) {
        /**
         * 新建对象仓库
         * name 对象仓库名
         * {keyPath:value}  指定主键     { autoIncrement: true } 自动生成主键(递增的整数)
        */
        objectStore = db.createObjectStore('person', { keyPath: 'id' });
        /**
         * 建立索引
         * 便于取值时,以此字段取值;不建立索引,只能以主键进行取值
        */
        objectStore.createIndex('name', 'name', { unique: false });
    }
}

4.新增数据

// 新增
function add() {
    /**
     * 新增数据
     * transaction([name],'') 新建事务([库名],权限)
     * objectStore(name) 仓库对象
     * add 写入记录
    */
    var request = db.transaction(['person'], 'readwrite')
        .objectStore('person')
        .add({ id: $('input[name=id]').val(), name: $('input[name=name]').val(), age: $('input[name=age]').val(), email: $('input[name=email]').val() });
	
	// 异步操作,可通过监听来查看执行结果
    request.onsuccess = function (event) {
        console.log('数据写入成功');
    };

    request.onerror = function (event) {
        console.log('数据写入失败');
    }
}

5.读取数据

// 读取
function get() {
    var id = $('input[name=getId]').val()
    /**
     * 取值
     * transaction([name]) 新建事务([库名])
     * objectStore(name)  仓库对象
     * get(value) 取值(主键值)
    */
    var request = db.transaction(['person'])
        .objectStore('person')
        .get(id);

    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('未获得数据记录');
        }
    };
}

如果我们建立了索引字段的话,我们就可以以索引字段取值了

/**
 * 建立索引
 * 便于取值时,以此字段取值;不建立索引,只能以主键进行取值
*/
objectStore.createIndex('name', 'name', { unique: false });
/**
 * 按索引取值
 * transaction([name]) 新建事务([库名])
 * objectStore(name)  仓库对象
 * index(name) 索引字段,需要建立索引字段
 * get(value) 取值(主键值) 
*/
 var request = db.transaction(['person'])
     .objectStore('person')
     .index('name')
     .get(1);

6.更新数据

// 更新
function update() {
    var request = db.transaction(['person'], 'readwrite')
        .objectStore('person')
        .put({ id: $('input[name=id]').val(), name: $('input[name=name]').val(), age: $('input[name=age]').val(), email: $('input[name=email]').val() });

    request.onsuccess = function (event) {
        console.log('数据更新成功');
    };

    request.onerror = function (event) {
        console.log('数据更新失败');
    }
}

7.删除数据

// 删除
function remove() {
     var id = $('input[name=getId]').val()
     
     var request = db.transaction(['person'], 'readwrite')
         .objectStore('person')
         .delete(id);

     request.onsuccess = function (event) {
         console.log('数据删除成功');
     };
 }

8.遍历数据

// 遍历
function getAll(){
    var objectStore = db.transaction('person').objectStore('person');

    objectStore.openCursor().onsuccess = function (event) {
        var cursor = event.target.result;

        if (cursor) {
            console.log('Id: ' + cursor.key + ';Name: ' + cursor.value.name + ';Age: ' + cursor.value.age + ';Email: ' + cursor.value.email);
            cursor.continue();
        } else {
            console.log('没有更多数据了!');
        }
    };
}

上面是遍历所有的数据,那么我们如果想去区间数据,怎么办?我们可以使用游标。游标通过对象仓库的 openCursor 方法创建并打开。

openCursor 方法接收两个参数,第一个是 IDBKeyRange 对象,该对象创建方法主要有以下几种:

// boundRange 表示主键值从1到10(包含1和10)的集合。
// 如果第三个参数为true,则表示不包含最小键值1,如果第四参数为true,则表示不包含最大键值10,默认都为false
var boundRange = IDBKeyRange.bound(1, 10, false, false);

// onlyRange 表示由一个主键值的集合。only() 参数则为主键值,整数类型。
var onlyRange = IDBKeyRange.only(1);

// lowerRaneg 表示大于等于1的主键值的集合。
// 第二个参数可选,为true则表示不包含最小主键1,false则包含,默认为false
var lowerRange = IDBKeyRange.lowerBound(1, false);

// upperRange 表示小于等于10的主键值的集合。
// 第二个参数可选,为true则表示不包含最大主键10,false则包含,默认为false
var upperRange = IDBKeyRange.upperBound(10, false);

openCursor 方法的第二个参数表示游标的读取方向,主要有以下几种:

next : 游标中的数据按主键值升序排列,主键值相等的数据都被读取
nextunique : 游标中的数据按主键值升序排列,主键值相等只读取第一条数据
prev : 游标中的数据按主键值降序排列,主键值相等的数据都被读取
prevunique : 游标中的数据按主键值降序排列,主键值相等只读取第一条数据
function getAll(){
    var objectStore = db.transaction('person').objectStore('person');
	var range = IDBKeyRange.bound(1,10);
    objectStore.openCursor(range,'next').onsuccess = function (event) {
        var cursor = event.target.result;

        if (cursor) {
            console.log('Id: ' + cursor.key + ';Name: ' + cursor.value.name + ';Age: ' + cursor.value.age + ';Email: ' + cursor.value.email);
            cursor.continue();
        } else {
            console.log('没有更多数据了!');
        }
    };
}

9.关闭和删除

// 关闭   db库对象
db.close();

//删除  name库名称
indexedDB.deleteDatabase(name);

参考:http://www.ruanyifeng.com/blog/2018/07/indexeddb.html
https://www.cnblogs.com/linxin/p/6772451.html

demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IndexDb</title>
</head>
<body>
    id:<input type="text" name="id" value="">
    name:<input type="text" name="name" value="">
    age:<input type="text" name="age" value="">
    email:<input type="text" name="email" value="">
    <input type="button" value="增加" onclick="add()">
    <input type="button" value="更新" onclick="update()">
    <br><br>
    id:<input type="text" name="getId" value="">
    <input type="button" value="读取" onclick="get()">
    <input type="button" value="删除" onclick="remove()">
    <br><br>
    <input type="button" value="遍历" onclick="getAll()">
</body>
<script src="https://www.jq22.com/jquery/jquery-3.3.1.js"></script>
<script>
    var db
    /**
     * 打开数据库,数据库不存在则默认新建
     * name  数据库名
     * version  版本号,没有则默认当前版本
    */
    var indexDb = window.indexedDB.open('ceshi', 1);   

    /**
     * 事件监听
     * error  失败
    */
    indexDb.onerror = function(event){
        console.log('数据库打开失败')
    }

    /**
     * 事件监听
     * success 成功
    */
    indexDb.onsuccess = function(event){
        db = indexDb.result
        console.log('数据库打开成功')
    }

    /**
     * 事件监听
     * upgradeneeded 版本升级;新建数据库从无到有可以触发该监听
    */
    indexDb.onupgradeneeded = function(event){
        db = event.target.result;
        var objectStore;
        // 判断是否存在对象仓库
        if (!db.objectStoreNames.contains('person')) {
            /**
             * 新建对象仓库
             * name 对象仓库名
             * {keyPath:value}  指定主键     { autoIncrement: true } 自动生成主键(递增的整数)
            */
            objectStore = db.createObjectStore('person', { keyPath: 'id' });
            /**
             * 建立索引
             * 便于取值时,以此字段取值;不建立索引,只能以主键进行取值
            */
            objectStore.createIndex('name', 'name', { unique: false });
        }
    }

    // 新增
    function add() {
        /**
         * 新增数据
         * transaction([name],'') 新建事务([库名],权限)
         * objectStore(name) 仓库对象
         * add 写入记录
        */
        var request = db.transaction(['person'], 'readwrite')
            .objectStore('person')
            .add({ id: $('input[name=id]').val(), name: $('input[name=name]').val(), age: $('input[name=age]').val(), email: $('input[name=email]').val() });

        request.onsuccess = function (event) {
            console.log('数据写入成功');
        };

        request.onerror = function (event) {
            console.log('数据写入失败');
        }
    }

    // 读取
    function get() {
        var id = $('input[name=getId]').val()
        /**
         * 取值
         * transaction([name]) 新建事务([库名])
         * objectStore(name)  仓库对象
         * get(value) 取值(主键值)
        */
        var request = db.transaction(['person'])
            .objectStore('person')
            .get(id);

        /**
         * 按索引取值
         * transaction([name]) 新建事务([库名])
         * objectStore(name)  仓库对象
         * index(name) 索引字段,需要建立索引字段
         * get(value) 取值(主键值) 
        */
        // var request = db.transaction(['person'])
        //     .objectStore('person')
        //     .index('name')
        //     .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('未获得数据记录');
            }
        };
    }

    // 更新
    function update() {
        var request = db.transaction(['person'], 'readwrite')
            .objectStore('person')
            .put({ id: $('input[name=id]').val(), name: $('input[name=name]').val(), age: $('input[name=age]').val(), email: $('input[name=email]').val() });

        request.onsuccess = function (event) {
            console.log('数据更新成功');
        };

        request.onerror = function (event) {
            console.log('数据更新失败');
        }
    }

    // 删除
    function remove() {
        var id = $('input[name=getId]').val()
        
        var request = db.transaction(['person'], 'readwrite')
            .objectStore('person')
            .delete(id);

        request.onsuccess = function (event) {
            console.log('数据删除成功');
        };
    }

    // 遍历
    function getAll(){
        var objectStore = db.transaction('person').objectStore('person');

        objectStore.openCursor().onsuccess = function (event) {
            var cursor = event.target.result;

            if (cursor) {
                console.log('Id: ' + cursor.key + ';Name: ' + cursor.value.name + ';Age: ' + cursor.value.age + ';Email: ' + cursor.value.email);
                cursor.continue();
            } else {
                console.log('没有更多数据了!');
            }
        };
    }

</script>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值