HTML and CSS Reference
In-Depth Information
// go!
Creating transactions—
and what they're good for
I've skipped over transactions so far. They're more than meets the
eye. They're not just the way to run queries; they serve a particu-
larly useful purpose. Transactions are like closed environments
in which you can run your queries. You can run just one query
or a group of queries within a transaction. In fact, you can't run
a query without being inside a transaction, since the executeSql
method is only available from the SQLTransaction object.
Possibly the most important aspect of the transactions is this: If
something fails inside the transaction (vanilla code or SQL state-
ments), then the whole transaction is rolled back. This means it's
as if the whole transaction block of code never happened.
The transaction method takes two arguments: The fi rst is the
contents of the transaction; the second, optional, is the error
handler if it's triggered. Below is a contrived example that shows
you how a transaction will rollback your failed transaction:
var db = openDatabase('foo', '1.0', 'foo', 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE foo (id unique, text)');
tx.executeSql('INSERT INTO foo (id, text) VALUES
¬ (1, “foobar”)');
db.transaction(function (tx) {
tx.executeSql('DROP TABLE foo');
// known to fail - so should rollback the DROP statement
tx.executeSql('INSERT INTO foo (id, text) VALUES
¬ (1, “foobar”)');
}, function (error) {
// error.message is “no such table: foo”
Search WWH ::

Custom Search