indexedDB

  • 个人博客,欢迎踩坑
  • 参考博客
  • indexDB中几个重要概念:
    • database:对应代码中的db
    • transaction(事务):对应代码中的transaction
    • objectStore:对应代码中的store,相对于sql中表的概念
    • objectStore的清除操作:clear
    • objectStore的增加操作:add
    • objectStore的删除操作:delete
    • objectStore的修改操作:put
    • objectStore的查询操作:get
    • key:主键,对应代码中的id
    • index:下标,对应代码中的nameIndex,ageIndex
    • cursor:游标,对应代码中的cursor
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button id='clear'>clear</button>
		<button id='add'>add</button>
		<button id='delete'>delete</button>
		<button id='put'>put</button>
		<button id='get'>get</button>
		<button id='getIndex'>getIndex</button>
		<button id='getCursor'>getCursor</button>
		<button id='indexAndCursor'>indexAndCursor</button>
		<button id='getKeys'>getKeys</button>
		<button id='getIndexs'>getIndexs</button>
		<script type="text/javascript">
			//indexDB是浏览器本地数据库,用于存储大量数据,存储格式为json
			var db;
			//1. 打开创建数据库:
			function openDB(name,version = 1){
				if(!window.indexedDB){
					alert('您的浏览器不支持indexDB');
					return;
				}
				var indexDBRequest = window.indexedDB.open(name,version);
				indexDBRequest.onerror = function(e){
					console.log('Open Error!');
				}
				indexDBRequest.onsuccess = function(e){
					db = indexDBRequest.result;//这里才是 indexedDB对象
					console.log('创建/打开数据库成功。db:%o',db);
				}
				// 注意: 只能请求>=当前数据库版本号的版本
				//  大于当前版本号, 则触发 onupgradeneeded, 
				//  小于当前版本号,则触发 onerror
				indexDBRequest.onupgradeneeded = function(e){
					console.log('DB version change to ' + version);
					db = indexDBRequest.result;
					//4. 有了数据库后我们自然希望创建一个表用来存储数据,但indexedDB中没有表的概念,而是叫 objectStore ,一个数据库中可以包含多个objectStore,objectStore是一个灵活的数据结构,可以存放多种类型数据。也就是说一个objectStore相当于一张表,里面存储的每条数据和一个键相关联。
					if(!db.objectStoreNames.contains('students')){
						//keyPath	对象,eg: {keyPath: ‘id’}
						// keyGenerator	任意值 eg: {autoincrement: true}
						/*
							自动生成主键:
							var objectStore = db.createObjectStore(
							  'students',
							  { autoIncrement: true }
							);
						*/
						var store = db.createObjectStore('students', { keyPath: 'id' });
						//删除objectStore
						// db.deleteObjectStore('storeName');
						
						//10. 创建索引
						// 在indexedDB中有两种索引,一种是自增长的int值,一种是keyPath:自己指定索引列
						store.createIndex('nameIndex','name',{unique:true});
						store.createIndex('ageIndex','age',{unique:false});
						//store中有三列数据:id | name | age
						console.log('第一次创建数据库或者更新数据库。db:%o',db);
					}
				}
			}
			window.onload = function(){
				openDB('dbname1');
			}
			
			//2. 删除数据库
			// window.indexedDB.deleteDatabase('dbname');
			
			//3. 关闭数据库
			// db.onclose = function(){
			// 	//do something...
			// };
			// db.close();
			
			//5. 保存数据到objectStore
			function saveData(storeName,data){
				//创建事务
				var transaction = db.transaction([storeName],'readwrite');
				//访问事务中的objectStore
				var store = transaction.objectStore(storeName);
				//data为数组
				// data.foreach((item,index) => {
				// 	store.add(item);//保存数据
				// });
				//data为对象
				var addRequest = store.add(data);
				addRequest.onsuccess = function (event) {
					console.log('save data done...',store);
				 };
				
				addRequest.onerror = function (event) {
					console.log('数据写入失败',store);
				}
				
			}
			document.getElementById('add').onclick = function(){
				saveData('students',{id:3,name:'张三3',age:18});
				saveData('students',{id:1,name:'张三1',age:27});
				saveData('students',{id:4,name:'张三4',age:35});
			};
			
			//6. 删除数据
			function deleteDataByKey(storeName,key){
				var transaction = db.transaction([storeName],'readwrite');
				var store = transaction.objectStore(storeName);
				var deleteRequest = store.delete(key);
				deleteRequest.onsuccess = function(e){
					console.log('delete data done...',store);
				}
				deleteRequest.onerror = function(e){
					console.log('delete data failed...',store);
				}
			}
			document.getElementById('delete').onclick = function(){
				deleteDataByKey('students',1);
			};
			
			//7. 修改数据
			//可以调用objectStore的put方法更新数据,会自动替换键值相同的记录,达到更新目的,没有相同的则添加。
			function putDataByKey(storeName,student){
				var transaction = db.transaction([storeName],'readwrite');
				var store = transaction.objectStore(storeName);
				store.put(student);
			}
			document.getElementById('put').onclick = function(){
				putDataByKey('students',{id:2,name:'张三2',age:26});
			};
			
			//8. 查找数据
			function getDataByKey(storeName,key){
				var transaction = db.transaction([storeName],'readwrite');
				var store = transaction.objectStore(storeName);
				var dataRequest = store.get(key);
				//异步的
				dataRequest.onsuccess = function(e){
					var data = e.target.result;
					console.log(data);
				}
			}
			document.getElementById('get').onclick = function(){
				getDataByKey('students',1);
			};
			
			//9. 清空数据
			function clearObjectStore(storeName){
				var transaction = db.transaction([storeName],'readwrite');
				var store  = transaction.objectStore(storeName);
				store.clear();
				console.log('clear data done...');
			}
			document.getElementById('clear').onclick = function(){
				clearObjectStore('students');
			};
			
			//11. 获取索引
			function getDataByIndex(storeName,indexName){
				var transaction = db.transaction([storeName],'readwrite');
				var store = transaction.objectStore(storeName);
				var index = store.index(indexName);//获取索引
				var request = index.get('张三1');
				request.onsuccess = function(e){
					var data = e.target.result;
					console.log(data);
				}
			}
			document.getElementById('getIndex').onclick = function(){
				getDataByIndex('students','nameIndex');
			};
			//12. 游标
			function fetchStoreByCursor(storeName){
				var transaction = db.transaction([storeName],'readwrite');
				var store = transaction.objectStore(storeName);
				var cursorRequest = store.openCursor();
				cursorRequest.onsuccess = function(e){
					var cursor = e.target.result;
					if(cursor){
						var currentData = cursor.value;
						console.log(currentData);
						cursor.continue();
					}
				}
			}
			document.getElementById('getCursor').onclick = function(){
				fetchStoreByCursor('students');
			};
			
			//13. 游标与index结合
			//获取age为26的student
			function getMultipleData(storeName){
			    var transaction=db.transaction([storeName]);
			    var store=transaction.objectStore(storeName);
			    var index = store.index("ageIndex");
			    var request=index.openCursor(IDBKeyRange.only(26))
			    request.onsuccess=function(e){
						var cursor=e.target.result;
						if(cursor){
							var student=cursor.value;
							console.log(student.id);
							cursor.continue();
						}
				}
			}
			//14. 指定游标范围
			// index.openCursor()/index.openKeyCursor() 方法在不传递参数的时候会获取objectStore所有记录,像上面例子一样我们可以对搜索进行筛选
			// 可以使用 IDBKeyRange 限制游标中值的范围,把它作为第一个参数传给 openCursor() 或是 openKeyCursor()
			// 
			// IDBKeyRange.only(value):只获取指定数据
			// IDBKeyRange.lowerBound(value,isOpen):获取最小是value的数据,第二个参数用来指示是否排除value值本身,也就是数学中的是否是开区间
			// IDBKeyRange.upperBound(value,isOpen):和上面类似,用于获取最大值是value的数据
			// IDBKeyRange.bound(value1,value2,isOpen1,isOpen2)
			// 获取名字首字母在B-E的student
			function getMultipleDataLimit(storeName,indexName){
			    var transaction=db.transaction([storeName]);
			    var store=transaction.objectStore(storeName);
			    var index = store.index(indexName);
			    var request=index.openCursor(IDBKeyRange.bound(18,27,false, true ));
			    request.onsuccess=function(e){
			        var cursor=e.target.result;
			        if(cursor){
			            var data=cursor.value;
			            console.log(data);
			            cursor.continue();
			        }
			    }
			}
			document.getElementById('indexAndCursor').onclick = function(){
				getMultipleDataLimit('students','ageIndex');
			};
			// 获取主键处于某一范围的值(不会对data进行deepClone)
			function getKeys(storeName){
			    var transaction=db.transaction([storeName]);
			    var store=transaction.objectStore(storeName);
				var keyRange = IDBKeyRange.bound(0, 3,false,false); // [0,3]
				var request = store.getAllKeys(keyRange);
			    request.onsuccess=function(e){
			        var cursor=e.target.result;
					console.log('getKeys...',cursor)
			    }
			}
			document.getElementById('getKeys').onclick = function(){
				getKeys('students');
			};
			// 获取index处于某一范围的值(不会对data进行deepClone)
			function getIndexs(storeName,indexName){
			    var transaction=db.transaction([storeName]);
			    var store=transaction.objectStore(storeName);
				var index = store.index(indexName);
				var request = index.openKeyCursor(IDBKeyRange.bound(18,27,false, false ));
				request.onsuccess = function(event) {
					var cursor = event.target.result;
					if(cursor) {
						console.log('cursor.key',cursor.key,'cursor.primaryKey',cursor.primaryKey)
						cursor.continue();
					} else {
					   console.log('All last names displayed.');    
					}
				};
			}
			document.getElementById('getIndexs').onclick = function(){
				getIndexs('students','ageIndex');
			};
			
		</script>
	</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值