日期:2014-05-16  浏览次数:20459 次

html5新功能 --操作WebDataBase--很实用

基于HTML5的Web DataBase 可以让你在浏览器中进行数据持久地存储管理和有效查询,假设你的离线应用程序有需要规范化的存储功能

本文讲述如何使用

1.新建一个网页,比如:test.html 内容如下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>web sql database</title>
<script type='text/javascript' src='jquery-1.4.3.js'></script> 
<script type="text/javascript">
$(function(){
        if (!window.openDatabase) {  
           alert("不支持");
        }  
        else {  
            initDB();  
            createTables();             
        }   
function initDB(){  
    var shortName = 'localDB';  
    var version = '1.0';  
    var displayName = 'localDB table';  
    var maxSize = 655350; // in bytes  
	//window.openDatabase("数据库名字", "版本","数据库描述",数据库大小);
    localDB = window.openDatabase(shortName, version, displayName, maxSize);  
}   
function createTables(){  
    var query = 'CREATE TABLE IF NOT EXISTS user(id INTEGER NOT NULL, username TEXT NOT NULL);';  
    try {  
        localDB.transaction(function(transaction){  
            transaction.executeSql(query, [], null, null);     
        });  
    }   
    catch (e) {  
	console.log("create table failed");
       alert("建表失败");
        return;  
    }  
}  
});
function btnClick(){
 var username = $("#username").val();
  try {  
        localDB.transaction(function(transaction){
            transaction.executeSql("insert into user(id,username) values(?,?)", [1,username]);  
        });		
    }   
    catch (e) {  
	console.log("insert into failed");
       alert("插入失败");
        return;  
    } 
	console.log("insert into success");
  //alert("insert into success");
 }
 function btnSelect(){
 localDB.transaction(function(tx) {
 tx.executeSql("select * from user", [],  
  function(tx, result) {
  $("#result").empty();
   for(var i = 0; i < result.rows.length; i++){ 
   $("#result").append('<b>' +result.rows.item(i)['id']+"------" +result.rows.item(i)['username']+ '</b><br />'); 
  } 
 }, function(){
  alert("error");
 }); 
});
 }
</script>
</head>
<body>
	<div id="my" style="height:100px;width:200px;border:1px solid red;">  
    <input type="text" name="username" id="username" value=""/>
	<br/>
	<button onclick="btnClick()">insert</button>
    </div>
	<div id="my1" style="height:300px;width:200px;border:1px solid red;">
	<button onclick="btnSelect()">select</button>
   <div id="result" style="height:300px;width:200px;border:1px solid blue;">
      </div>
    </div>
</body>
</html>

2.注意引入js文件哦

3.已经ok,直接打开网页浏览  最好用谷歌浏览器,然后 按 F12键 查看 Resources --Web SQ