基于HTML5的Web?DataBase?可以讓你在瀏覽器中進行數據持久地存儲管理和有效查詢,假設你的離線應用程序有需要規范化的存儲功能
本文講述如何使用核心方法openDatabase、transaction、executeSql
1.新建一個網頁,比如:test.html 內容如下:
[html]?view plaincopy
- <!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鍵 查看 Application --Web SQL 下面有新建的數據庫以及表