`
18211103738
  • 浏览: 82295 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

html5的indexedDB数据库操作实例

阅读更多

效果:



 代码:

StringUtil.js

 

//去除字符串中间空格 
String.prototype.Trim = function() { 
	return this.replace(/(^s*)|(s*$)/g, ""); 
} 
//去除字符串左侧空格 
String.prototype.LTrim = function() { 
	return this.replace(/(^s*)/g, ""); 
} 
//去除字符串右侧空格 
String.prototype.RTrim = function() { 
	return this.replace(/(s*$)/g, ""); 
}
//去除字符串中所有空格(包括中间空格,需要设置第2个参数为:g) 
function Trim(str,is_global){ 
	var result; 
	result = str.replace(/(^s+)|(s+$)/g,""); 
	if(is_global.toLowerCase()=="g") 
	result = result.replace(/s/g,""); 
	return result; 
} 

 indexedDB.js

window.onload = function(){
	if(!window.indexedDB){
		window.indexedDB = window.mozIndexedDB || window.webkitIndexedDB;
	}
	
	var db = null;
	var request = indexedDB.open("mydb");
	request.onupgradeneeded = function(e){
		//db = request.result;
		db = e.target.result;
		createObjectStore(db);
	}
	
	function createObjectStore(db){
		if(db.objectStoreNames.contains("customer")){
			db.deleteObjectStore("customer");
		}
		
		var objectStore = db.createObjectStore("customer",{keyPath:"id",autoIncrement:true});
		
		objectStore.createIndex("name","name",{unique:false});
		objectStore.createIndex("email","email",{unique:true});
		
		objectStore.add({name: "Tom", sex: "male", age: 34, email: "tom@facebok.org"});
		objectStore.add({name: "Jiny", sex: "female", age: 25, email: "jiny@home.org"});
		objectStore.add({name: "Liam", sex: "male", age: 23, email: "liam@163.com"});
	}
	
	request.onsuccess = function(e){
		db = e.target.result;
		if(!db.version=="1.0"){
			var request = db.setVersion("1.0");
			request.onsuccess = function(e){
				createObjectStore(db);
				showDataByCursor();
			}
			request.onerror = function(e){
				alert(e);
			}
		}else{
			showDataByCursor();
		}
	}
	
	function showDataByCursor(objectStore){
		if(!objectStore){
			var transaction = db.transaction(["customer"]);
			objectStore = transaction.objectStore("customer");
		}
		console.log("Store-Name : "+objectStore.name);
		console.log("Store-KeyPath : "+objectStore.keyPath);
		
		var request = objectStore.openCursor();
		request.onsuccess = function(e){
			var cursor = e.target.result;
			if(cursor){
				console.log(cursor.key);
				console.log(cursor.value);
				var data = cursor.value;
				data.id = cursor.key;
				showInTable(data);
				cursor.continue();
			}
		}
		request.onerror = function(e){
			console.log("ERROR");
		}
	}
	
	var table = document.getElementsByTagName("table")[0];
	function showInTable(data){
		//table.childNodes
		var tbody = table.children[1];
		//tbody = document.getElementsByTagName("tbody")[0];
		var tr = document.createElement("tr");
		var td_id = createTd(data,"id")
		var checkBox=document.createElement("input");
		checkBox.setAttribute("type","checkbox");
		checkBox.setAttribute("name","check");
		var textNode = td_id.childNodes[0];
		checkBox.setAttribute("id",textNode.nodeValue);
		//td_id.removeChild(textNode);
		td_id.appendChild(checkBox);
		//td_id.appendChild(textNode);
		tr.appendChild(td_id);
		var td_name = createTd(data,"name");
		tr.appendChild(td_name);
		var td_sex = createTd(data,"sex");
		tr.appendChild(td_sex);
		var td_age = createTd(data,"age");
		tr.appendChild(td_age);
		var td_email = createTd(data,"email");
		tr.appendChild(td_email);
		tbody.appendChild(tr);
	}
	
	function createTd(data,key){
		var td = document.createElement("td");
		td.contentEditable = "true";
		var namedNodeMap = td.attributes;
		var attrKey = document.createAttribute("key");
		attrKey.value = key;
		namedNodeMap.setNamedItem(attrKey);
		var attrValue = document.createAttribute("value");
		attrValue.value = data[key];
		namedNodeMap.setNamedItem(attrValue);
		var attrType = document.createAttribute("type");
		attrType.value = typeof(data[key]);
		namedNodeMap.setNamedItem(attrType);
		td.innerText = data[key];
		td.onblur = function(event){
			console.log(this.parentNode.firstElementChild.innerText);
			console.log(this.innerText.LTrim().RTrim());
			console.log(this.attributes["value"].value);
			console.log(this.attributes["key"].value);
			console.log(this.innerText);
			if(this.attributes["value"].value != this.innerText.LTrim().RTrim()){
				 saveOrUpdate(event.target);	//或saveOrUpdate(this)
			}
		}
		return td;
	}

	function saveOrUpdate(obj){
		var id = obj.parentNode.firstElementChild.innerText;
		var transaction = db.transaction(["customer"],"readwrite");
		var objectStore = transaction.objectStore("customer");
		
		var request = objectStore.get(parseInt(id));
		//var range = IDBKeyRange.only("Donna");
		//var request = objectStore.index("name").openCursor(range);
		request.onsuccess = function(event){
			if(event.target.result){
				//objectStore.delete(id);
				var data = event.target.result;
				console.log("Update : " + data);
				var value = obj.attributes["type"].value=="number"?parseInt(obj.innerText):obj.innerText;
				data[obj.attributes["key"].value] = value;
				var updateRequest = objectStore.put(data);
				updateRequest.onsuccess = function(event){
					//console.log(event.target);
					console.log("UPDATE SUCCESS");
				}
				updateRequest.onerror = function(event){
					console.log("UPDATE ERROR");
				}
			}else{
				var data = {};
				var tds = obj.parentNode.children;
				for(var i=0;i<tds.length;i++){
					var td = tds[i];
					var key = td.attributes["key"].value;
					data[key] = td.attributes["type"].value=="number"?parseInt(td.innerText):td.innerText;
				}
				console.log("Add : " + data);
				var saveRequest = objectStore.add(data);
				saveRequest.onsuccess = function(){
					console.log("SAVE SUCCESS");
				}
				saveRequest.onerror = function(){
					console.log("SAVE ERROR");
				}
			}
		}
		request.onerror = function(event){
			alert(event);
		}
	}
	
	/*搜索*/
	var name = document.getElementsByName("name")[0];
	var email = document.getElementsByName("email")[0];
	var select = document.getElementsByTagName("button")[0];
	
	select.onclick = function(event){
		var value_name = name.value.LTrim().RTrim();
		var value_email = email.value.LTrim().RTrim();
		
		var transaction = db.transaction(["customer"],"readonly");
		var objectStore = transaction.objectStore("customer");
		
		var tbody = table.children[1];
		var elements = tbody.children;
		var count = elements.length;
		for(var i=0;i<elements.length;){	//动态移除,没有i++,始终移除第一个
			tbody.removeChild(elements[i]);
		}
		if(value_name=="" && value_email==""){
			var request = objectStore.openCursor();
			request.onsuccess = function(event){
				var cursor = event.target.result;
				if(cursor){
					showInTable(cursor.value)
					cursor.continue();
				}
				console.log("GETALL SUCCESS");
			};
			request.onerror = function(event){
				console.log(event.target);
				console.log("GETALL ERROR");
			};
		}else{
			if(value_name!=""){
				var range = IDBKeyRange.only(value_name);
				var request = objectStore.index("name").openCursor(range);
				request.onsuccess = function(event){
					
					var cursor = event.target.result;
					if(cursor){
						console.log("key : "+cursor.key);
						console.log("value : "+cursor.value);
						showInTable(cursor.value)
						cursor.continue();
					}
					console.log("SELECT BY NAME SUCCESS");
				}
				request.onerror = function(event){
					console.log("SELECT BY NAME ERROR");
				}
			}
			if(value_email!=""){
				var range = IDBKeyRange.only(value_email);
				var request = objectStore.index("email").openCursor(range);
				request.onsuccess = function(event){
					
					var cursor = event.target.result;
					if(cursor){
						console.log("key : "+cursor.key);
						console.log("value : "+cursor.value);
						showInTable(cursor.value)
						cursor.continue();
					}
					console.log("SELECT BY EMIAL SUCCESS");
				}
				request.onerror = function(event){
					console.log("SELECT BY EMAIL ERROR");
				}
			}
		}
	}
	
	/*删除和清空*/
	var checkAll = document.getElementsByName("checkAll")[0];
	var btnDelete = document.getElementsByName("delete")[0];
	var btnClear = document.getElementsByName("clear")[0];
	checkAll.onclick = function(event){
		var checkBoxs = document.getElementsByName("check");
		console.log(checkBoxs);
		if(this.checked==true){
			for(var i=0;i<checkBoxs.length;i++){
				checkBoxs[i].checked = true;
			}
		}else{
			for(var i=0;i<checkBoxs.length;i++){
				checkBoxs[i].checked = false;
			}
		}
	}
	btnDelete.addEventListener("click",function(event){
		var checkBoxs = document.getElementsByName("check");
		console.log(checkBoxs);
		var transaction = null;
		var objectStore = null;
		var request = null;
		for(var i=0;i<checkBoxs.length;i++){
			var checkBox = checkBoxs[i];
			if(checkBox.checked == true){
				if(request == null){
					transaction = db.transaction(["customer"],"readwrite");
					objectStore = transaction.objectStore("customer");
				}
				var id = parseInt(checkBox.attributes["id"].value);
				console.log("checked : "+id);
				request = objectStore.get(id);
				request.onsuccess = function(event){
					if(event.target.result){
						var record = event.target.result;
						objectStore.delete(record.id);
						for(var j=0;j<checkBoxs.length;j++){
							if(checkBoxs[j].attributes["id"].value-record.id==0){
								var tr = checkBoxs[j].parentElement.parentElement;
								var tbody = checkBoxs[j].parentElement.parentElement.parentElement;
								tbody.removeChild(tr);
								break;
							}
						}
						console.log("DELETE SUCCESS");
					}
				};
				request.onerror = function(event){
					console.log("DELETE ERROR");
				};
			}
		}
	});
	btnClear.addEventListener("click",function(event){
		var objectStore = db.transaction(["customer"],"readwrite").objectStore("customer");
		var request = objectStore.clear();
		request.onsuccess = function(event){
			console.log("CLEAR SUCCESS");
			objectStore.openCursor().onsuccess = function(event){
				var tbody = table.children[1];
				var elements = tbody.children;
				for(var i=0;i<elements.length;){	//动态移除,没有i++,始终移除第一个
					tbody.removeChild(elements[i]);
				}
				var cursor = event.target.result;
				if(cursor){
					var data = cursor.value;
					data.id = cursor.key;
					showInTable(data);
					cursor.continue();
				}
				console.log("SHOW SUCCESS");
			}
		}
		request.onerror = function(event){
			console.log("CLEAR ERROR");
		}
	});
};

 indexedDB.html

<!doctype html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>IndexedDB</title>
		<script type="text/javascript" src="StringUtil.js"></script>
		<!--<script type="text/javascript" src="jquery-1.8.3.js"></script>-->
		<script type="text/javascript" src="indexedDB.js"></script>
	</head>
	<body>
		<div>
			<label>姓名:<input type="text" name="name" value="" style="width:50px;height:15px;"/></label>
			<label>邮箱:<input type="text" name="email" value="" style="width:80px;height:15px;"/></label>
			<button type="button">查询</button>
		</div>
		<table>
			<thead>
				<tr>
					<th>ID</th>
					<th>姓名</th>
					<th>性别</th>
					<th>年龄</th>
					<th>邮箱</th>
				</tr>
			</thead>
			<tbody>
			</tbody>
			<tfoot>
				<tr>
					<td colspan="5">
						<label style="font-size:14px"><input type="checkbox" name="checkAll"/>全选</label>
						<input type="button" name="delete" value="删除选中"/>
						<input type="button" name="clear" value="清空数据库"/>
					</td>
				</tr>
			</tfoot>
		</table>
	</body>
</html>

 

  • 大小: 45.5 KB
分享到:
评论

相关推荐

    HTML5中indexedDB 数据库的使用实例

    要连接IndexedDB数据库,首先需要调用`indexedDB.open`方法,传入数据库名和版本号。例如: ```javascript var request = indexedDB.open('dbName', 1); ``` 请求对象上的`onsuccess`和`onerror`事件分别用于...

    html5 web IndexedDB通讯录的实现

    HTML5的IndexedDB是Web应用程序的一个重要特性,它提供了一个在客户端存储大量结构化数据的本地数据库,支持离线应用和高性能的数据检索。这个通信录的实现就是利用IndexedDB进行数据管理和交互的一个实例。 首先,...

    indexedDB实例

    IndexedDB是HTML5的一项重要功能,它提供了一个客户端数据库系统,用于在用户的浏览器中存储大量结构化数据。这个本地存储机制不同于传统的Cookie或localStorage,它允许开发者创建复杂的数据库索引,进行高效的数据...

    html5本地数据库教程(indexed)

    HTML5的IndexedDB是一个强大的本地数据存储解决方案,尤其适合需要大量结构化数据的Web应用程序。这个API遵循W3C的标准,允许开发者在客户端存储大容量数据,并通过索引实现高效检索。与DOM Storage相比,IndexedDB...

    IndexedDB详细demo

    - **数据库(Database)**:每个IndexedDB实例都是一个独立的数据库,数据库由用户创建并命名。 - **对象存储(Object Store)**:类似于关系数据库中的表,用于存储数据。每个对象存储都有一个唯一的名字,并可以...

    android与html5的交互——数据库操作,UI操作,以及html5的localStorage、定位功能

    HTML5引入了Web SQL Database和IndexedDB作为离线存储解决方案,允许在浏览器端存储大量数据。在Android应用中,通过使用Cordova(前身是PhoneGap,如DroidGapDemo所示)框架,可以无缝集成这些功能。Web SQL ...

    html5 初试 indexedDB(推荐)

    首先,我们来看如何打开或创建一个IndexedDB数据库。在JavaScript中,我们通过`window.indexedDB`全局对象来访问IndexedDB API。以下代码展示了打开数据库的基本步骤: ```javascript var indexedDB = window....

    html5本地存储web sql数据库操作增删查找实例

    尽管Web SQL已被Web Storage(包括localStorage和sessionStorage)和IndexedDB所取代,但它在一些旧项目或特定场景下仍然有其价值。理解并熟练掌握Web SQL的使用,对于开发高效、可靠的Web应用程序至关重要。

    HTML5操作WebSQL数据库的实例代码

    HTML5中的WebSQL是一种在客户端浏览器中使用的数据库存储机制,它允许开发者在浏览器中进行SQL数据库的查询和操作,类似本地数据库的操作方式。下面将详细介绍WebSQL数据库的知识点。 首先,WebSQL并不是HTML5的一...

    html5离线存储实例

    使用IndexedDB,开发者可以通过创建数据库、对象存储、索引来操作数据。以下是一个简单的示例: ```javascript // 打开或创建数据库 let request = indexedDB.open("myDatabase", 1); request.onsuccess = ...

    PhoneGap操作数据库实例

    PhoneGap借助WebSQL或IndexedDB为移动应用提供了本地存储能力,但在这个实例中,我们主要关注SQLite,因为它是PhoneGap的默认数据库。 首先,PhoneGap应用中的数据库操作依赖于SQLite JavaScript API,它是一个轻量...

    html5使用本地sqlite数据库

    虽然现在Web SQL Database已经被废弃,取而代之的是IndexedDB,但在一些旧的或特定的项目中,它仍然被广泛使用。 在HTML5中使用SQLite数据库,你需要通过JavaScript来操作。以下是一些关键的步骤和概念: 1. **...

    HTML5 JS API教程 本地数据库

    HTML5的离线存储特性,特别是Web Storage(包括localStorage和sessionStorage)以及IndexedDB,为开发者提供了一种更强大、更灵活的方式来存储和管理本地数据。 首先,我们来看看`localStorage`。它提供了一个持久...

    Dexie.js基本使用-前端大容量存储IndexedDB 的包装库,可运行代码

    Dexie.js是一个轻量级的JavaScript库,它为浏览器中的IndexedDB提供了一个易用且强大的API。IndexedDB是Web浏览器提供的一个原生的本地存储解决方案,允许应用程序在客户端存储大量数据。然而,由于其复杂的API,...

    JavaScript操作SQLite数据库Demo

    然而,JavaScript也可以用于客户端的数据存储,这得益于HTML5引入的离线存储技术,比如Web SQL数据库或者更现代的IndexedDB。在本示例中,我们将探讨如何使用JavaScript直接操作SQLite数据库。 SQLite是一个轻量级...

    WebSQL到IndexedDB的示例:待办事项列表示例,显示如何将WebSQL转换为IndexedDB

    3. **迁移数据**:编写脚本将WebSQL中的数据迁移到新的IndexedDB数据库中,可能需要处理异步操作和错误处理。 4. **更新读写操作**:将所有读取和写入数据的函数从WebSQL的SQL语句修改为IndexedDB的API调用。 5. **...

    HTML5本地存储和本地数据库实例详解

    IndexedDB是现代浏览器更推荐的本地数据库方案,它提供了更高级别的数据存储能力,支持B树索引,可以存储大量结构化数据,并且支持异步操作,避免阻塞页面。IndexedDB允许创建多个数据库,每个数据库包含多个对象...

    内存数据库 dexie.js

    dexie.js是一个JavaScript库,它作为HTML5 IndexedDB的一个轻量级封装器,提供了类SQL的语言接口,使得在Web应用中使用IndexedDB变得更加便捷。 IndexedDB是浏览器原生提供的一种NoSQL型数据库,用于在客户端持久化...

    使用HTML5 IndexDB存储图像和文件的示例

    首先,通过indexedDB.open()方法打开或创建一个IndexedDB数据库实例。这个方法会返回一个IDBOpenDBRequest对象,该对象包含了onsuccess和onerror事件处理器,分别用来处理数据库打开成功和失败的情况。文章强调了...

Global site tag (gtag.js) - Google Analytics