Database API
At present, there are multiple ways to store structured data using HTML5, including the WebSQL API implemented by Webkit browsers and the competing IndexedDB API spearheaded by Firefox.
WebSQL API
WebSQL provides structured data storage by implementing an SQL-like syntax. Currently, implementations have centralized around SQLite, but that isn't a specific requirement.
There isn't a "createDatabase" function in WebSQL. The function openDatabase optimistically creates a database with the given parameters if one doesn't already exist. To create a database name myDB, we would need to make a call in the form
var db = openDatabase("myDB", "1.0", "myDB Database", 100000);
where we pass "myDB" as the name, assign the version "1.0", specify a display name of "myDB Database", and give it an estimated size of 100KB. We could have optionally specified a callback to be executed upon creation. Figure 1-2 shows the content of the Chrome Developer Tools Storage tab, which we will cover in more detail in Chapter 2, "Setting Up Your Development Environment," after executing the preceding line of code.
Figure 1-2 Storage tab showing a created database
In the window to the right, we can run arbitrary SQL code, as shown in Figure 1-3, where we created a table, inserted some information, and ran a query.
Figure 1-3 Storage tab showing SQL statements
Although not universally supported, the specification does call out the existence of both asynchronous and synchronous database connections and transactions. Our current example creates an asynchronous connection; to create a synchronous one, we would call openDatabaseSync with the same parameters. After the initial connection, there is no distinction when it comes to database transactions besides calling transaction(...) for read/write transactions and readTransaction for read-only transactions.
A word of caution: Synchronous connections are not well supported and, in general, you should structure your code to run asynchronously.
IndexedDB API
IndexedDB stores objects directly in object stores. This makes it easier to implement JavaScript versions of NoSQL databases, like those of the object databases MongoDB, CouchDB, and SimpleDB. At the time of this writing, the implementations of the APIs weren't synchronized and used different naming schemes and strictness to the specification. The Internet Explorer implementation requires an ActiveX plugin. I encourage you to check out http://nparashuram.com/trialtool/index.html#example=/ttd/IndexedDB/all.html to see some examples in action on Firefox, Chrome, and Internet Explorer. The Chrome code in most cases will work seamlessly on Safari.