indexedDB是H5规范里的浏览器内置数据库,是nosql数据库的一种。因为另一种数据库Web SQL不再受W3C支持,所以还得学习下这个。

基本情况

  1. 兼容性:ie11及以上都支持,
  2. W3C是这么说的
  3. 调试的时候个人觉得firefox最方便

示例代码

html代码:

<form>
  userId:<input type="text" name="uid" id="uId"/><br/>
  userName:<input type="text" name="uname" id="uName"/><br/>
  email:<input type="email" name="uemail" id="uEmail"/><br/> <br/>
  <input type="button" value="Add" id="addBut"/>
  <input type="button" value="Delete" id="delBut"/>
  <input type="button" value="Update" id="updateBut"/>
  <input type="button" value="Search" id="searBut"/>
</form>

<hr/>

<button id='showAll'>Show All</button>

<table width="60%">
  <tr>
    <td width="10%">uid</td>
    <td width="20%">uname</td>
    <td width="30%">uemail</td>
  </tr>
</table>

<table class="desc" width="60%">
</table>

js代码:

<script src="http://apps.bdimg.com/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
  $(document).ready(function () {

    //判断浏览器是否支持indexedDB
    window.indexedDB = window.indexedDB || window.mozIndexedDB
    || window.webkitIndexedDB || window.msIndexedDB;

    if (window.indexedDB) { //如果支持
      console.log("支持");

      //创建请求打开数据库,不能直接打开。demoDB是数据库名;3是版本号。
      var request = window.indexedDB.open('demoDB', 3);
      var db;

      //onupgradeneeded事件:第一次打开页面初始化数据库时,或在当有版本号变化时调用。
      request.onupgradeneeded = function (event) {
        db = event.target.result;
        //创建一个存储,名称为user
        var objectStore = db.createObjectStore('user', {keyPath:'uid'});
        // 创建一个email索引。不能有相同的 email 地址,所以使用一个 unique 索引。
        objectStore.createIndex("uemail", "uemail", {unique:true});
        console.log('运行onupgradeneeded... :)');
      };

      //成功回调
      request.onsuccess = function (event) {
        db = event.target.result;
        console.log('创建(请求)数据库成功 :)');
      };

      //失败回调
      request.onerror = function (event) {
        console.log('创建(请求)数据库出错 :(', event);
      };

    } else {//如果不支持
      console.log('The browser does not support indexedDB :)')
    }

    //增
    $('#addBut').click(function () {
      var uidVal = $('#uId').val();
      var unameVal = $('#uName').val();
      var emailVal = $('#uEmail').val();
      //首先需要创建一个事务,具有读写权限。在indexedDB里任何的存取对象的操作都需要放在事务里执行
      var transaction = db.transaction(['user'], 'readwrite');
      var objectStore = transaction.objectStore('user').add({uid:uidVal, uname:unameVal, uemail:emailVal});
      transaction.oncomplete = function (event) {
        console.log('新记录增加成功 :)');
      };
      transaction.onerror = function (event) {
        console.log('新记录增加出错 :(', event);
      }
    });

    //删
    $('#delBut').click(function () {
      var uidVal = $('#uId').val();
      var request = db.transaction(['user'], 'readwrite').objectStore('user').delete(uidVal);
      request.onsuccess = function (event) {
        console.log('数据删除成功 :)');
      };
      request.onerror = function (event) {
        console.log('删除出错 :(', event);
        //console.log('删除出错 :(',event.target.errorCode);
      };
    });

    //改
    $('#updateBut').click(function () {
      var uidVal = $('#uId').val();
      var unameVal = $('#uName').val();
      var emailVal = $('#uEmail').val();
      var request = db.transaction(['user'], 'readwrite').objectStore('user').put({
        uid:uidVal,
        uname:unameVal,
        uemail:emailVal
      });
      request.onsuccess = function (event) {
        console.log('修改成功 :)');
      };
      request.onerror = function (event) {
        console.log('修改出错 :(');
      }
    });

    //查
    $('#searBut').click(function () {
      var uidVal = $('#uId').val();
      var transaction = db.transaction(['user'], 'readwrite');
      var objectStore = transaction.objectStore('user').get(uidVal);
      objectStore.onsuccess = function (event) {
        $('#uName').val(objectStore.result.uname);
        $('#uEmail').val(objectStore.result.uemail);
        console.log('查询成功 :)');
      };
      objectStore.onerror = function (event) {
        console.log('查询出错 :(', event.target.errorCode);
      }
    });

    //查 取出所有数据
    $('#showAll').click(function () {
      var str = '';
      var transaction = db.transaction(['user']);
      var objectStore = transaction.objectStore('user');
      objectStore.openCursor().onsuccess = function (event) {
        var cursor = event.target.result;
        if (cursor) {
          str += '<tr><td with="10%">' + cursor.key + '</td><td with="20%">' + cursor.value.uname + '</td><td with="30%">' + cursor.value.uemail + '</td></tr>';
          $('.desc').html(str);
          cursor.continue();
        } else {
          // console.log('No more datas... :(');
        }
      }
    });

  });
</script>

标签: 数据库, h5, html5, indexedDB