Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Working with Web SQL CHAPTER 16 587


var db = openDatabase('Library', '2.0', 'My library', 5 * 1024 * 1024);
db.transaction(function(t){
t.executeSql("SELECT * FROM authors", [], displayResults)
});

Because you are only retrieving data, you just as easily could have used the
readTransaction method instead of the transaction method.
db.readTransaction(function(t){
t.executeSql("SELECT * FROM authors", [], displayResults)
});

Quick check
■■The following statement has a syntax error in the second step of the transaction
in this migration script (misspelled CREATE as CRATE). What do you expect will
happen because of this migration script?
function migrateDB(transaction) {
transaction.executeSql("CREATE TABLE authors(firstName TEXT)");
transaction.executeSql("CRATE TABLE books(title TEXT)");
}

var db = openDatabase('Library', '1.0', 'My library', 5 * 1024 * 1024);
db.changeVersion('1.0' , '2.0', migrateDB)

Quick check answer
■■Neither table will be created.

Filtering results
You rarely want to read every row from a database table; most of the time, you need to limit
those results to specific criteria. Because current implementations are based on SQLite, you
have all the power of a mature database engine to help you.
For example, you can add a WHERE clause to return only records with a specific lastName
value, as follows.
var db = openDatabase('Library', '2.0', 'My library', 5 * 1024 * 1024);
var lastName = 'Defoe';
db.transaction(function(t){
t.executeSql("SELECT * FROM authors WHERE lastName = ?", [lastName], displayResults)
});

You might like to find all authors whose last name starts with the letter D. To do so, use the
LIKE keyword along with the ‘%’ wildcard.
var lastName = 'D%';
db.transaction(function(t){
t.executeSql("SELECT * FROM authors WHERE lastName LIKE ?", [lastName],
Free download pdf