The Web SQL database API isn’t actually part of the HTML5 specification, but it is part of the suite of specifications that allows us developers to build fully fledged web applications, so it’s about time we dig in and check it out.
What’s in the box?
If you haven’t guessed from the overly verbose specification title, Web SQL Databases is a spec that brings SQL to the client side. If you have a back-end developer’s background, then you’ll probably be familiar with SQL and happy as a pig in muck. If not, you might want to learn some SQL before you start hacking around, Google’s your friend here.
The specification is based around SQLite (3.1.19), but having come from MySQL myself, it’s all pretty much the same (sorry for the sweeping statement!).
For an example of Web SQL Databases working, have a look at the Twitter HTML5 chatter demo I put together. It uses SQL and the WHERE clause to narrow down the recent chat about HTML5 on Twitter (it will work in Safari, Chrome and Opera 10.50).
There are three core methods in the spec that I’m going to cover in this article:
-
openDatabase
-
transaction
-
executeSql
Support is a little patchy at the moment. Only Webkit (Safari, SafariMobile and Chrome) and Opera 10.50 (ATOW alpha on Mac) support web databases. Fellow Doctor Bruce Lawson has told me that Firefox are holding off as they feel there’s a better implementation than SQLite (though I hope it’s similar, whatever they pick). Either way, I’d definitely recommend checking out the SQLite documentation for the functions that are available.
Because of this patchy support and the simple fact that Webkit had implemented the database spec some time ago, the spec on the W3C is now slightly ahead of the implementations in Safari, while Webkit is still catching up. On the other hand, since Opera has only just added support, it’s closer to the spec (I’ll mention the differences as we go along).
Nonetheless, it’s fun to play with, so let’s get playing!
Creating and Opening Databases
If you try to open a database that doesn’t exist, the API will create it on the fly for you. You also don’t have to worry about closing databases.
To create and open a database, use the following code:
var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
I’ve passed four arguments to the openDatabase
method. These are:
- Database name
- Version number
- Text description
- Estimated size of database
The missing feature of openDatabase
(I’m not sure when it was added) is the fifth argument:
- Creation callback
The creation callback will be called if the database is being created. Without this feature, however, the databases are still being created on the fly and correctly versioned.
The return value from openDatabase
contains the transaction methods, so we’ll need to capture this to be able to perform SQL queries.
Estimated database size
From the tests I’ve run, only Safari prompts the user if you try to create a database over the size of the default database size, 5MB. The prompt is shown the image below, asking whether you want to grant the database permission to scale up to the next size of database — 5, 10, 50, 100 and 500MB. Opera, on the other hand, builds the database without complaining, which I expect might change later as it’s still in alpha.
Versions
I could be wrong, but everything I’ve tested so far says that versioning in SQL databases is borked. The problem is this:
If you upgrade your database to version 2.0 (e.g., there are some important schema changes since version 1.0), how do you know which visitors are on version 1.0 and which are on version 2.0?
The version number is a required argument to openDatabase
, so you must know the version number before you try to open it. Otherwise, an exception is thrown.
Also, changeVersion
, the method to change the database version, is not fully supported in Webkit. It works in Chrome and Opera, but not in Safari or Webkit. Regardless, if I can’t determine which version of database the user is on, then I can’t upgrade the user.
A possible workaround is to maintain a state database, something like the ‘mysql’ database in MySQL. This way, you would only have one version of this state database, and within this you would record the current version of any databases that control your application. It’s a hack, but it works.
Transactions
Now that we’ve opened our database, we can create transactions. Why bother with transactions instead of just running our SQL? Transactions give us the ability to rollback. This means that if a transaction — which could contain one or more SQL statements — fails (either the SQL or the code in the transaction), the updates to the database are never committed — i.e. it’s as if the transaction never happened.
There are also error and success callbacks on the transaction, so you can manage errors, but it’s important to understand that transactions have the ability to rollback changes.
The transaction is simply a function that contains some code:
var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
db.transaction(function (tx) {
// here be the transaction
// do SQL magic here using the tx object
});
I recently uploaded a demo to html5demos.com that demonstrates a transaction rollback in action: Web SQL database rollback demo
In the nightly builds of the browsers, we also have db.readTransaction
, which allows only read statements to run on the database. I assume there are performance benefits to using a read-only readTransaction
instead of a read/write transaction
, most probably to do with table locking.
Now that we’ve got our transaction object (named tx
in my example) we’re ready to run some SQL!
executeSql
This is the funnel of love for all your SQL goodness. executeSql
is used for both read and write statements, includes SQL injection projection, and provides a callback method to process the results of any queries you may have written.
Once we have a transaction object, we can call executeSql
:
var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE foo (id unique, text)');
});
This will now create a simple table called “foo” in our database called “mydb”. Note that if the database already exists the transaction will fail, so any successive SQL wouldn’t run. So we can either use another transaction, or we can only create the table if it doesn’t exist, which I’ll do now so I can insert a new row in the same transaction:
var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "synergies")');
});
Now our table has a single row inside it. What if we want to capture the text from the user or some external source? We’d want to ensure it can’t compromise the security of our database (using something nasty like SQL injection). The second argument to executeSql
maps field data to the query, like so:
tx.executeSql('INSERT INTO foo (id, text) VALUES (?, ?)', [id, userValue]);
id
and userValue
are external variables, and executeSql
maps each item in the array argument to the “?”s.
Finally, if we want to select values from the table, we use a callback to capture the results:
tx.executeSql('SELECT * FROM foo', [], function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).text);
}
});
(Notice that in this query, there are no fields being mapped, but in order to use the third argument, I need to pass in an empty array for the second argument.)
The callback receives the transaction object (again) and the results object. The results object contains a rows
object, which is array-like but isn’t an array. It has a length, but to get to the individual rows, you need to use results.rows.item(i)
, where i
is the index of the row. This will return an object representation of the row. For example, if your database has a name
and an age
field, the row will contain a name
and an age
property. The value of the age
field could be accessed using results.rows.item(i).age
.
That’s all you should need to get started with Web SQL Databases. I’m certain that mini JavaScript libraries are going to emerge to help support working with databases. If you want to find out more about SQL databases (shameless self promotion begins) I just finished the storage chapter for Introducing HTML5, which I’m writing with fellow Doc Bruce, so check that bad boy out too!
相关推荐
Web SQL Database是HTML5早期的本地存储解决方案之一,允许Web应用程序在用户的浏览器中存储大量结构化数据,类似于关系型数据库。这个通信录示例就是对Web SQL Database用法的一个直观展示。 首先,我们来看如何...
通过一个例子说明 Web SQL Database 的基本用法。它首先调用 openDatabase 创建了名为“fooDB”的数据库。然后使用 transaction 执行两条 SQL 语句。第一条 SQL 语句创建了名为“foo”的表,第二条 SQL 语句向表中...
HTML5中ExtJS和Web SQL Database的使用 一、前言 伴随着移动通信技术的快速发展,智能手机逐渐成为人们的日常消费品。在Android平台上进行HTML5网页程序的设计与开发中,如何使用Android平台的SDK和HTML5网页版...
其中,HTML5的`canvas`元素和Web SQL Database是两个重要的组成部分,它们在本案例中结合使用,实现了动态图形绘制和客户端数据存储的功能。 `canvas`元素是HTML5中的一个画布,它允许开发者通过JavaScript进行像素...
Web SQL数据库概述 Web SQL数据库是HTML5中的一种客户端数据库解决方案,使用SQL语言来操作客户端...8. Web SQL Database是HTML5中的一种强大且灵活的客户端数据库解决方案,能够满足我们在Web开发中的各种需求。
### HTML5离线存储之Web SQL 随着HTML5标准的不断完善和浏览器技术的进步,Web开发领域迎来了诸多新特性,其中Web SQL数据库就是一种用于客户端的数据存储解决方案。虽然WebDatabase规范官方宣布不再进行维护,但其...
这个“sql-web.zip”压缩包包含一个名为“sql web.html”的文件,很显然,它是关于如何使用HTML5的Web SQL数据库进行数据存储的教程或者示例。 Web SQL数据库是HTML5的一个弃用特性,尽管如此,它在一些老旧的或...
WebSQL和LocalStorage是两种在浏览器端进行数据存储的技术,它们都是HTML5标准的一部分,为Web应用提供了离线存储的能力。 WebSQL,全称Web SQL Database,是一个基于SQLite的关系型数据库系统,它允许开发者在用户...
在提供的压缩包文件中,WebSql.htm是展示这些操作的HTML页面,webSQL.js包含了上述JavaScript代码,而jquery-1.4.1.min.js是用于简化DOM操作的jQuery库。web sql说明.doc可能是对Web SQL数据库更详细的文档介绍,...
HTML5的Web SQL是一种在浏览器本地存储数据的技术,尽管它并未被纳入HTML5规范,但仍然在某些浏览器中得到支持,比如Chrome、Safari和Opera。Web SQL提供了一个API,使得开发者可以使用SQL来操作客户端数据库,这...
HTML5 Web SQL 是一个独立的规范,专门设计用于在客户端浏览器中存储和操作数据的API。尽管它并未被纳入HTML5标准,但它提供了一种利用SQL语法在本地创建和管理数据库的方法,尤其适用于离线应用或者需要大量本地...
HTML5应用开发技术中的Web SQL数据库是一个离线存储解决方案,特别适用于需要在用户浏览器中存储大量结构化数据的Web应用程序。尽管HTML5还提供了localStorage和sessionStorage,它们只能存储简单的键值对,不适合...
Web SQL 数据库是 HTML5 中的一种存储机制,它允许开发者在客户端存储数据,并提供了一个类似于关系型数据库的存储机制。下面是使用 Web SQL 数据库的相关知识点: 1. 使用 Web SQL 数据库简介 Web SQL 数据库是一...
HTML5中的WebSQL是一种在客户端浏览器中使用的数据库存储机制,它允许开发者在浏览器中进行SQL数据库的查询和操作,类似本地数据库的操作方式。下面将详细介绍WebSQL数据库的知识点。 首先,WebSQL并不是HTML5的一...
在本课程"PHP5与MYSQL5 WEB开发详解DATABASE1"中,我们将深入探讨这两个核心技术在构建Web应用程序中的应用。PHP5作为服务器端脚本语言,是动态网站开发的常用工具,而MySQL5则是一个功能强大的关系型数据库管理系统...
本文主要介绍了基于HTML5的手机端记事本设计,主要采用了HTML5的Web SQL Database和jQuery技术完成记事本的新建、记事、删除等功能。 HTML5 本地数据库概述 HTML5 引入了 Web SQL Database 概念,它使用 SQL 来...