好记性不如烂笔头。indexedDB的API记录下来,备用。代码来源传智播客,在此感谢。

indexedDB是HTML5-WebStorage的重要一环,是一种轻量级NOSQL数据库。相比web sql(sqlite)更加高效,包括索引、事务处理和健壮的查询功能。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body></body>
<script type="text/javascript">
  // 获取indexdb对象,为了兼容性的写法
  // 1、获取对象
  window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
  window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
  window.IDBCursor = window.IDBCursor || window.webkitIDBCursor || window.msIDBCursor;

  //2.定义数据库的基本信息
  var dbInfo = {
    dbName: 'testdb',
    dbVersion: '1001',
    dbInstance: {}
  };

  //3.创建数据库
  var dbContent = window.indexedDB.open(dbInfo.dbName, dbInfo.dbVersion);

  //数据库版本更新
  dbContent.onupgradeneeded = function(e){
    console.log('数据库版本号修改了');
    //4.创建数据库表(store)
    var _db = e.target.result;  //获取数据库
    var storeNames = _db.objectStoreNames;  //获取所有表

    if(!storeNames.contains('cart')){
      // 创建表,参数:表名,表结构
      _db.createObjectStore('cart', {
        keyPath: 'goodsId',   //索引
        autoIncrement: true
      })
    }
  }

  //数据库连接成功
  dbContent.onsuccess = function(e) {
    console.log('数据库连接成功')
    //5.增删查改操作写在这里
    var _db = e.target.result;
    var trans = _db.transaction(['cart'], 'readwrite');
    var store = trans.objectStore('cart');

    //基于请求的,注意一次只能做一个操作
    //添加数据
//    var req = store.add({
//      goodsId: '102',
//      price: 999.99,
//      name: '衬衫',
//      size: 'M'
//    });

    //修改数据
//    var req = store.put({
//      goodsId: '102',
//      price: 666,
//      name: '衣服',
//      size: 'XXL'
//    });

      //删除数据
    //var req = store.delete('100');

    //删除所有数据
    //var req = store.clear();

//    req.onsuccess = function(e){
//      console.log(e);
//      console.log('操作数据成功');
//    }
//
//    req.onerror = function(e){
//      console.log('操作数据失败' + e);
//    }

    // 查询所有数据
//    var cursor = store.openCursor();
//    var data = [];
//    cursor.onsuccess = function(e){
//      console.log(e)
//      var result = e.target.result;
//      if(result && result !== null){
//        data.push(result.value);
//      }
//      console.log(data)
//    }
//    cursor.onerror = function(e){
//      console.log(e);
//    }

  }

  //数据库连接失败
  dbContent.onerror = function(e){
    alert('连接数据库失败');
  }
</script>
</html>
View Code