Html5数据库API是以一个独立规范形式出现,它包含三个核心方法:
1、openDatabase:这个方法使用现有数据库或创建新数据库创建数据库对象。
2、transaction:这个方法允许我们根据情况控制事务提交或回滚。
3、executeSql:这个方法用于执行真实的SQL查询。
打开数据库
openDatabase方法可以打开已经存在的数据库,不存在则创建:
var db = openDatabase('mydatabase', '2.0', my db', 2 * 1024);
openDatabasek中五个参数分别为:数据库名、版本号、描述、数据库大小、创建回调。创建回调没有也可以创建数据库。
执行查询
database.transaction()函数用来查询,下面将在mydatabase数据库中创建表t1:
var db = openDatabase(' mydatabase ', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS t1 (id unique, log)');
});
插入操作
var db = openDatabase('mydatabase', '2.0', my db', 2 * 1024); db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS t1 (id unique, log)');
tx.executeSql('INSERT INTO t1 (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO t1 (id, log) VALUES (2, "logmsg")');
});
在插入新记录时,我们还可以传递动态值,如:
var db = openDatabase(' mydatabase ', '2.0', 'my db', 2 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS t1 (id unique, log)');
tx.executeSql('INSERT INTO t1 (id,log) VALUES (?, ?'), [e_id, e_log]; //e_id和e_log是外部变量 });
读操作
如果要读取已经存在的记录,我们使用一个回调捕获结果,代码如下:
var db = openDatabase(mydatabase, '2.0', 'my db', 2*1024); db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS t1 (id unique, log)');
tx.executeSql('INSERT INTO t1 (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO t1 (id, log) VALUES (2, "logmsg")');
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM t1, [], function (tx, results) { var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++){
alert(results.rows.item(i).log );
}
}, null);
});
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
msg = '<p>Log message created and row inserted.</p>';
document.querySelector('#status').innerHTML = msg;
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++){
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}, null);
});
</script>
</head>
<body>
<div id="status" name="status">Status Message</div>
</body>
</html>
效果:
演示二
HTML布局:
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="txtName" id="txtName" required/></td>
</tr>
<tr>
<td>标题:</td>
<td><input type="text" name="txtTitle" id="txtTitle" required/></td>
</tr>
<tr>
<td>留言:</td>
<td><input type="text" name="txtWords" id="txtWords" required/></td>
</tr>
</table>
<input type="button" value="保存" id="btnSave"/>
<hr/>
<input type="button" value="展示所哟数据" onclick="showAllTheData();"/>
<table id="tblData">
</table>
JS代码(需要jQuery):
<script type="text/javascript">
function initDatabase() {
var db = getCurrentDb();//初始化数据库 if(!db) {alert("您的浏览器不支持HTML5本地数据库");return;}
db.transaction(function (trans) {//启动一个事务,并设置回调函数 //执行创建表的Sql脚本 trans.executeSql(
"create table if not exists Demo(uName text null,title text null,words text null)",
[],
function (trans, result) { //结果回调 },
function (trans, message) {//消息的回调函数alert(message);}); }
);
});
}
$(function () {//页面加载完成后绑定页面按钮的点击事件 initDatabase();
$("#btnSave").click(function () {
var txtName = $("#txtName").val();
var txtTitle = $("#txtTitle").val();
var txtWords = $("#txtWords").val();
var db = getCurrentDb();
//执行sql脚本,插入数据 db.transaction(function (trans) {
trans.executeSql("insert into Demo(uName,title,words) values(?,?,?) ", [txtName, txtTitle, txtWords], function (ts, data) {
}, function (ts, message) {
alert(message);
});
});
showAllTheData();
});
});
function getCurrentDb() {
//打开数据库,或者直接连接数据库参数:数据库名称,版本,概述,大小 //如果数据库不存在那么创建之 var db = openDatabase("myDb", "1.0", "it's to save demo data!", 1024 * 1024); ;
return db;
}
//显示所有数据库中的数据到页面上去 function showAllTheData() {
$("#tblData").empty();
var db = getCurrentDb();
db.transaction(function (trans) {
trans.executeSql("select * from Demo ", [], function (ts, data) {
if (data) {
for (var i = 0; i < data.rows.length; i++) {
appendDataToTable(data.rows.item(i));//获取某行数据的json对象 }
}
}, function (ts, message) {alert(message);var tst = message;});
});
}
function appendDataToTable(data) {//将数据展示到表格里面 //uName,title,words var txtName = data.uName;
var txtTitle = data.title;
var words = data.words;
var strHtml = "";
strHtml += "<tr>";
strHtml += "<td>"+txtName+"</td>";
strHtml += "<td>" + txtTitle + "</td>";
strHtml += "<td>" + words + "</td>";
strHtml += "</tr>";
$("#tblData").append(strHtml);
}
</script>
效果:
谢谢关注!