HTML and CSS Reference
In-Depth Information
var db;
if (window.openDatabase) {
db = openDatabase('mydb', '1.0', 'My first database',
¬ 2 * 1024 * 1024);
}
It's as simple as that. Next you need to set up a new table in the
database, which—like all other operations we'll be doing on this
database—is done through the
executeSql
method.
Creating tables
When creating tables (or performing any other action on the
database), you must start a database “transaction” and, within
the callback, execute the relevant SQL. The transaction call-
back receives an argument containing the transaction object,
which allows you to run SQL statements and run the
executeSql
method (
tx
in the following example). This is done using the
database object that was returned from
openDatabase
and by
calling the transaction method:
var db;
if (window.openDatabase) {
db = openDatabase('tweetdb', '1.0', 'All my tweets',
¬ 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE tweets (id, date, tweet)');
});
}
The
executeSql
method takes four arguments, of which only the
first is required:
1.
SQL
2.
Arguments to SQL (such as field values)
3.
Success callback
4.
Error callback
In the previous example, you use only the SQL parameter. Of
course, if the statement to create a table runs and the table
already exists, an error is triggered, but since you're not catch-
ing it and it doesn't affect the program flow, in this instance you
don't care.