<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>利用索引获取数据</title>
<script>
var myDB={
name:"helloindexDB",
version:1,
db:null
}
function openDB(name,version){
var version =version || 1;
var request=widow.indexedDB.open(name,version);
request.onerror=function(e){
}
request.onsuccess=function(e){
myDB.db=e.target.result;
}
//以下是 对 数据表 进行操作
request.onupgradeneeded=function(e){
var db=e.target.result;
//如果没有 student 表
if(!db.objectStoreNames.contains("students"))
{
//创建student表,并设置id为key
var story=db.createObjectStore("students",{keyPath:"id"});
//创建字段
story.createIndex("nameIndex","name",{unique:true} );
story.createIndex("ageIndex","age",{unique:false});
}
}
}
var students=
[
{
id:101,
name:"aa",
age:10
},
{
id:102,
name:"bb",
age:11
},
{
id:103,
name:"cc",
age:12
}
]
function addData(db,storeName){
var transaction=db.transaction(storeName,"readwrite");//读取权限
var store=transaction.objectStore(storeName);
for(var i=0;i<students.length;i++)
{
store.add(students[i]);
}
}
//执行操作
openDB(myDB.name,myDB.version);
setTimeout(function(){
addData(myDB.db,"students");
},1000);
//以上是上一节内容
//通过 姓名 来获取数据
function getDataByIndexName(db,storeName){
var transaction=db.transaction(storeName);//通过链接来获取数据表(数据仓库)
var store=transaction.objectStore(storeName);//实例化数据表
var index=store.index("nameIndex");//获取索引
index.get("aa").onsuccess=function(e){
var student=e.target.result;
console.log(student.name+"--"+student.age+"--"+student.id);
}
}
//执行 getDataByIndexName
setTimeout(function(){
getDataByIndexName(myDB.db,"students");
},1000)
//通过 年龄 来获取数据
function getDataByIndexAge(db,storeName){
var transaction=db.transaction(storeName);//通过链接来获取数据表(数据仓库)
var store=transaction.objectStore(storeName);
var index=store.index("ageIndex");
index.get(11).onsuccess(function(e){
var student=e.target.result;
console.log("姓名:"+student.name+"--年龄:"+student.age+"--id:"+student.id);
})
}
//执行 getDataByIndexAge
setTimeout(function(){
getDataByIndexAge(myDB.db,"students");
},1000)
{#
综上所述:通过name来获取的数据是可以获得相同name的数据,但是age不行。因为name是唯一的,
age不是唯一的 ,
所以 要用 “游标” 来解决
#}
</script>
</head>
<body >
</body>
</html>

本文介绍了如何在HTML5的IndexedDB数据库中利用索引获取数据。通过创建索引`nameIndex`和`ageIndex`,分别展示了根据姓名和年龄获取数据的方法。文章强调,由于年龄不是唯一字段,所以当需要根据年龄获取多个匹配项时,需要使用游标进行操作。

1541

被折叠的 条评论
为什么被折叠?



