HTML and CSS Reference
Be wary of versioning!
The implementations of Web SQL Database support a slightly older version of the Web SQL Database API,
and more specifically the versioning model.
Although the specification describes how you can manage and migrate from different versions of the data-
base, this hasn't been implemented very well. The model requires you to know the version of the database
on the user's machine to be able to open it. The problem is that if you have migrated through multiple ver-
sions of your database, there's no way to determine which version the visiting user is on, and opening the
database with the wrong version number throws an INVALID_STATE_ERROR . You could wrap each of the
open database attempts in a try/catch, but you'd require one for each version of your database, something
that could get very messy after a few years of upgrades.
Using the Web SQL Database API
The typical database API usage involves opening the database
and then executing some SQL. Note that if I were working with
a database on the server side, I would typically close the data-
base connection. This isn't required with the database API, and
in fact there's no way to do this. That said, you can open a data-
base multiple times without any adverse effect.
Opening and creating databases
By opening a database for the first time, the database is cre-
ated. You can have only one version of your named database
on the domain at any one time, so if you create version 1.0 you
can't then open 1.1 without the database version having been
specifically changed by your application. For the rest of this
chapter, I'm going to ignore versioning and stick to one version
only due to the previously stated warning.
var db = openDatabase('mydb', '1.0', 'My first database',
¬ 2 * 1024 * 1024);
The latest version of the SQL databases spec includes a fifth
argument to openDatabase , but this isn't supported in any of the
browsers right now. It offers a callback when the database is
created for the first time. You've now created a new database
called “mydb,” version 1.0, with a text description of “My first
database,” and you've set the size of the data to 2 MB (this has
to be set in bytes which is why I multiply 2 * 1024 * 1024). To
ensure that the app works and detects support for the Web SQL
Database API, you should also test for database support in the
browser, so wrap the code with the openDatabase test: