webdevRefinery Forum: HTML5 Local Databases or WebSQL - webdevRefinery Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

User is offline Renegade 

  • Group: Members
  • Posts: 719
  • Joined: 08-March 10
  • Expertise:HTML,CSS,PHP,Javascript,Node.js,SQL,Graphics

Posted 08 October 2010 - 06:40 PM (#1)

HTML5 Local Databases or WebSQL


Getting started with HTML5's new local databases.
Posted Image

Posted Image
Posted ImagePosted Image


So you've probably heard a lot about the new HTML, HTML5. This is tutorial is about one of my favorite new specifications from it, client-side databases. This new specification will be popular, web-apps are now changing the web and portability it the key. People don't have the internet everywhere (yet) so this is where client-side functionality comes in, these databases allow for storage offline and when connection is available, update online.


Posted Image


» Creating the database


 openDatabase(shortName, version, displayName, maxSize);


We use the openDatabase to create and open a database. This function which has a few specific parameters.
  • shortName - This is basically the name you will use to reference the database. Keep it simple and distinguishable.
  • version - This is a string, so anything is generally accepted i.e using the alpha (α) or beta (β) symbols
  • displayName - Just for readability, has no real effect on the database.
  • maxSize - An integer which states the maximum size of the database in bytes



» Querying the database

database.transaction(
 function (transaction) {
 	//Usage: transaction.executeSql(_QUERY_, [vars], callback);
	//Create Table
	transaction.executeSql("CREATE TABLE foobar(id, foo, bar)");
	//Insert data into database
	transaction.executeSql("INSERT INTO table_name(foo, bar) VALUES(?, ?)", ['foo', 'bar']);
} );


The transaction function is basically the wrapper for the executeSql function. ExecuteSql is the vital function for querying the database. The parameters for executeSql is just the SQL query.

» Getting the data

//Your query
function(transaction) {
	transaction.executeSql("SELECT * FROM sample", [], retrieveData); //The retrieveData function is where the data is sent/returned to in parameters (transation, results)
});


The key to retrieving the data is to send it to a function to parse and use/display it. As in the example above, I use a function called retriveData. The data is sent as a parameter in the function.

function retrieveData(transaction, results) {
	//Usage: results.rows.item(int)[columnName];
	
	//Loop through the data, similar to using PHP etc.
	for(var i = 0; i < results.rows.length; i++) {
	    //This will return the data from row i (the integers from loop) from the column 'foobar' 
	    var data = results.rows.item(i)['foobar']
	}
}


To access the data, we need to use the results parameter. The data is a bit different from accessing normal Javascript variables as it needs the keywords rows and item(). Item(int) needs an integer to select a specific row, it does not return every row. This will return a Javascript object with the data in that row. After we have our row selected, we select a column we want the data returned from, so we add our column name after item() e.g item(2)['foo'] This is exactly the same as if you were retrieve data in a normal JS Object.

Posted Image

Okay, so this is where the actual tutorial starts. In this we will create a simple Web App to add and remove data from a simple, local database. Lets get started!

Posted Image

YAYMusic, this is the fictional (but awesome) app we will be creating. We will create a simple song addition (Not actual MP3, but just names etc.) and rating system. Nothing mildly complex.

What we need:
  • Check compatibility
  • To create the database and tables
  • To load songs and rating already added (if any) on load.
  • Form to add songs to database
  • Rating functionality on each song

Posted Image
We need to firstly check compatibility. Only a few browsers, as listed above are currently supporting local databases which meaning's we'd like to tell the user why there is no content coming up or why errors are popping up, basically wtf is going on. So, Although it is messy, I find it handy to manage if you completely wrap your code in and [if/else] statement.

if(!window.openDatabase){
	setAnError("Woops, your browser doesn't support Database. Please update/change your browser");
	} else {
	//Run main you code
	}


What it's really saying: IF it's not possible to open database => Display error ELSE it is possible to open database => Run code.


Posted Image
Now that we know that the user supports Local Databases, we are set for creating one. For this we'll need to decide on it's name, version, long name and maximum size. This is done with the openDatabase function. It does exactly what it says on the tin, it opens or creates a database.

function createDatabase() {
 	var shortName = 'yaymusic';
 	var version = '1.0';
 	var displayName = 'YAYMusic Database';
 	var maxSize = 100000; //The variables to open the database
 	return yaymusic = openDatabase(shortName, version, displayName, maxSize); //This will return the database
 	}
}

var db = createDatabase(); //Create the DB and set it to a global variable for easy access


var yaymusic = openDatabase(shortName, version, displayName, maxSize);

This is where the database is created, as you can see in the above code, each of its parameters (shortName, version etc.) are defined above it. To check if you have created your database, you can open your inspector window and check the storage tab, we should see our 'yaymusic' database as clear as daylight.

Posted Image


Posted Image
So once you have your database created, we need to populate it with some tables! So what would we need for storing a song?
  • id - Primary key
  • name - text
  • artist - text
  • album - text
  • genre - text
  • rating - Integer
Lets create our query,

CREATE TABLE songlist(
	id INTEGER PRIMARY KEY,
	name TEXT,
	artist TEXT,
	album TEXT,
	genre TEXT,
	rating INTEGER
);


Now that we have our query constructed, we should put it to the database, in a nice and tidy function. Later on we may want to remove and the add the table.


//Lets make some tables
function createTables(db) {
	db.transaction(
		function(transaction) {
		
			//Query to create database
			transaction.executeSql('CREATE TABLE IF NOT EXISTS songlist(id INTEGER PRIMARY KEY, name TEXT, artist TEXT, album TEXT, genre TEXT, rating INTEGER, user TEXT);');
			
			});
		}


This function will be called when the app is first loaded, and will create a table IF NOT EXISTS. As mention above, when we will need to delete all of the records, we will destroy the table then re-add it, therefore needing to call the createTables function.

STILL IN PROGRESS, IN THE MEANTIME
(Of course this tutorial is subject to mistakes and mishaps (my own stupidity), please correct me on anything incorrect.)

Posted Image
Posted Image
(Local Database capable browsers only i.e Chrome, Opera, Safari)

GithubTwitterDribbbleForrst
We all die. The goal isn't to live forever. The goal is to create something that will.

Array(16).join({}-{}) + " Batman!";
1


User is offline AbrarSyed 

  • Yeah, I know, I am just that awesome...
  • Group: Members
  • Posts: 685
  • Joined: 03-July 10
  • LocationIL, USA
  • Expertise:HTML,CSS,PHP,Javascript,Graphics

Posted 08 October 2010 - 07:18 PM (#2)

That is so cool!!!!!!!!! But one things I need to know is where the stuff will be stored, and how to add columns/values like MySQL (if possible). One more thing, how are we supposed to access it after we make the table..

PS: how is this any different from a cookie???


MINECRAFT PARTY
67.175.138.40:443 OFFLINE
0


User is offline Tim 

  • Group: Members
  • Posts: 86
  • Joined: 16-August 10
  • LocationSomerset, UK
  • Expertise:HTML,CSS

Posted 08 October 2010 - 08:18 PM (#3)

Looking forward to this tutorial, local storage is one of the best things about the new html5 spec IMO.
timmw.co.uk - not much to see here (yet)
0


User is offline Daniel15 

  • dan.cx
  • Group: Moderators
  • Posts: 3038
  • Joined: 17-April 10
  • LocationMelbourne, Australia
  • Expertise:HTML,CSS,PHP,Java,Javascript,SQL

Posted 09 October 2010 - 02:40 AM (#4)

Not to intrude, but here's a code sample I wrote a while back:

Spoiler


Not going to write an explanation, as that'll come in this tutorial I'm sure. The code was rushed as I was using it as part of a HTML5 presentation at work, it could be cleaned up quite a bit (like use "this" instead of "DBDemo") :) and the column names are based off the standards at work. :P

Back when I tested it (a few months ago), it ONLY properly worked in Opera. Chrome could create/open the database but not select any data :blink:. Things might have changed now.
Daniel15! :D
Repeat after me: jQuery is not JavaScript. It is not the answer to every JavaScript-related question. When you have to write some JavaScript, do not instantly react with "Oh, I'll do that with jQuery!"

javascript:alert((''+[][[]])[!+[]+!+[]]+(![]+[])[+!+[]]+(''+!+[]/[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(''+!![])[+!+[]+!![]+!![]]+(![]+[])[!+[]+!+[]]+(+!+[])+(!+[]+!+[]+!+[]+!+[]+!+[]))

View PostKyek, on 16 November 2011 - 11:14 AM, said:

Daniel15 is ruining my life D:

View Postmorrison_levi, on 30 September 2011 - 04:10 PM, said:

They added more features to tables because. . . oh, yeah, they do have valid uses! Ever heard of data? We do still use that. :)
1


User is offline Renegade 

  • Group: Members
  • Posts: 719
  • Joined: 08-March 10
  • Expertise:HTML,CSS,PHP,Javascript,Node.js,SQL,Graphics

Posted 09 October 2010 - 05:24 PM (#5)

View PostDaniel15, on 09 October 2010 - 02:40 AM, said:

Not to intrude, but here's a code sample I wrote a while back:

Spoiler


Not going to write an explanation, as that'll come in this tutorial I'm sure. The code was rushed as I was using it as part of a HTML5 presentation at work, it could be cleaned up quite a bit (like use "this" instead of "DBDemo") :) and the column names are based off the standards at work. :P

Back when I tested it (a few months ago), it ONLY properly worked in Opera. Chrome could create/open the database but not select any data :blink:. Things might have changed now.


Awesome Daniel, I'm sure this will help plenty of people wanting to learn about the databases! :D
GithubTwitterDribbbleForrst
We all die. The goal isn't to live forever. The goal is to create something that will.

Array(16).join({}-{}) + " Batman!";
0


User is offline Renegade 

  • Group: Members
  • Posts: 719
  • Joined: 08-March 10
  • Expertise:HTML,CSS,PHP,Javascript,Node.js,SQL,Graphics

Posted 14 October 2010 - 11:56 AM (#6)

Added cool demo that I spent a good while designing and tweaking, take a look at it. This is what the tutorial is based on and of course, it will explain it thoroughly. :)
GithubTwitterDribbbleForrst
We all die. The goal isn't to live forever. The goal is to create something that will.

Array(16).join({}-{}) + " Batman!";
0


User is offline Daniel15 

  • dan.cx
  • Group: Moderators
  • Posts: 3038
  • Joined: 17-April 10
  • LocationMelbourne, Australia
  • Expertise:HTML,CSS,PHP,Java,Javascript,SQL

Posted 18 October 2010 - 04:49 AM (#7)

Wow! This post was listed in CodeProject's weekly newsletter this week!!
Posted Image

Congratulations :D

Edit: Screenshot from my email is above. It's also online at http://www.codeproje....aspx?mlid=8378
(it's a great newsletter, contains really interesting links every week. I'd recommend it :P)

This post has been edited by Daniel15: 18 October 2010 - 04:52 AM

Daniel15! :D
Repeat after me: jQuery is not JavaScript. It is not the answer to every JavaScript-related question. When you have to write some JavaScript, do not instantly react with "Oh, I'll do that with jQuery!"

javascript:alert((''+[][[]])[!+[]+!+[]]+(![]+[])[+!+[]]+(''+!+[]/[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(''+!![])[+!+[]+!![]+!![]]+(![]+[])[!+[]+!+[]]+(+!+[])+(!+[]+!+[]+!+[]+!+[]+!+[]))

View PostKyek, on 16 November 2011 - 11:14 AM, said:

Daniel15 is ruining my life D:

View Postmorrison_levi, on 30 September 2011 - 04:10 PM, said:

They added more features to tables because. . . oh, yeah, they do have valid uses! Ever heard of data? We do still use that. :)
0


User is offline Quinn 

  • More pew-pew, less QQ
  • Group: Members
  • Posts: 1180
  • Joined: 08-March 10
  • LocationPalmyra, PA, USA
  • Expertise:HTML,PHP,Javascript

Posted 18 October 2010 - 06:00 AM (#8)

Renegade also showed me a twitter status from SmashingMagazine about this post as well.
"1st plane could've been an accident, 2nd plane was an attack, 3rd plane was an act of war" - George W. Bush
"Poli meaing many, tics meaning blood-sucking butt lumps" - Anonymous
<Imp> [F3ar 40]  [PWNbear 17]  [magik 15]  [dissident 10]  [mark 7]

View PostKyek, on 07 February 2011 - 07:11 AM, said:

Though anyone who thinks Europe is a country should be smacked in the face. By a train.
0


User is online Hyde 

  • Totally Ubermensch
  • Group: Members
  • Posts: 1272
  • Joined: 08-March 10
  • Expertise:HTML,CSS,PHP

Posted 18 October 2010 - 06:07 AM (#9)

That's nice, however I'm not sure I'll use it yet.
Hyde | HTML | CSS | PHP & SQL | Basic JavaScript | Objective-C
0


User is offline mtcoder 

  • Group: Members
  • Posts: 1
  • Joined: 18-October 10

Posted 18 October 2010 - 08:40 AM (#10)

One key thing to be aware of though, is security be mindful that its easy to hack client side storage. While all of these things are great with greatness comes responsibility, and I fear people won't be responsible with what is stored locally.

I have already ran into a few site that wanted to try and save "account" based information locally. There is little if any protection to the local storage. Outside of that though it can make a great way to provide storage in a database style. A few things I have storage are user's site preferences, a couple tracking things, like number of times user navigates on the site, with details about where / what they clicked on. Gives me more details on site navigation based on a user. To keep privacy, all I store with to the user though a bunch of database ID's locally, which relate to tables on my server.

My fear though comes from even what the original post here states, offline storage. Um just what do you plan to do with offline storage when the user is offline? Only thing you could do is provide a javascript / html5 download which allows people to do something like manage an address book. But that isn't great cause the moment they get a virus and need to clear their internet storage files its gone. Heck a user could even do it just trying to clean up space on their machine, by accident.

It's a great feature don't get me wrong, but just be careful with what you store and how you plan to provide value by doing so. It's not really designed for offline use, but more of a structured local cache to improve performance of your site / remove bandwidth / load.
1


User is online Kyek 

  • Founder of wdR
  • Group: Administrators
  • Posts: 4834
  • Joined: 20-February 10
  • LocationPhiladelphia, PA, USA
  • Expertise:HTML,CSS,PHP,Java,Javascript,Node.js,SQL

Posted 18 October 2010 - 09:49 AM (#11)

This is a killer guide! Well worth the attention it's getting :)

(Speaking of which, you've singlehandedly doubled wdR's unique visitor count last week ;-))
0


User is offline Mo3 

  • Brogrammer
  • Group: Moderators
  • Posts: 1928
  • Joined: 21-July 10
  • LocationStuttgart, Germany
  • Expertise:PHP,Java,Javascript,Python,Ruby on Rails,Node.js

Posted 18 October 2010 - 09:54 AM (#12)

Quote

10 Replies
8368 Views


:)
Mo3|Javascript|Ruby|Python|AndroidSDK
0


User is online Kyek 

  • Founder of wdR
  • Group: Administrators
  • Posts: 4834
  • Joined: 20-February 10
  • LocationPhiladelphia, PA, USA
  • Expertise:HTML,CSS,PHP,Java,Javascript,Node.js,SQL

Posted 09 February 2011 - 08:49 AM (#13)

Thanks for throwing the deprecation notice on this :). That'll clear up some confusion.

Small note, though... it's deprecated, not depreciated. Lots of people make that mistake :). "Depreciated" means that something's monetary value is lessened. "Deprecated", in software terms, means obsolete and limited-if-any continuing support.
0


User is online Cyril 

  • Get off my canvas!
  • Group: Members
  • Posts: 2314
  • Joined: 03-August 10
  • LocationParis, France
  • Expertise:HTML,CSS,PHP,Javascript,Node.js,Graphics

Posted 09 February 2011 - 08:51 AM (#14)

Haha. Kyek got my report :P

html, css, php, python, graphics
centideo :: cntdin :: github :: twitter :: dribbble :: forrst
0


User is offline Koen 

  • Leroy Jenkins
  • Group: Members
  • Posts: 2409
  • Joined: 10-March 10
  • Locationthe Netherlands
  • Expertise:HTML,CSS,Javascript,Graphics

Posted 09 February 2011 - 08:59 AM (#15)

View PostFireCat, on 09 February 2011 - 08:51 AM, said:

Haha. Kyek got my report :P
I wanted to as well :P
Twitter: @KoenKlaren
0


User is offline gibbonweb 

  • 兄ヨハネス
  • Group: Members
  • Posts: 1615
  • Joined: 23-June 10
  • LocationMunich(DE)
  • Expertise:HTML,CSS,PHP,Javascript,Python,SQL,Graphics

Posted 09 February 2011 - 09:20 AM (#16)

So, um, if its deprecated... what's the new thingy then?
caution: may contain irony.
NOTE that quality posts can only be guaranteed if a +rep advance payment has been made.
gibbonweb | github | hdr photography

Posted Image
0


User is online Kyek 

  • Founder of wdR
  • Group: Administrators
  • Posts: 4834
  • Joined: 20-February 10
  • LocationPhiladelphia, PA, USA
  • Expertise:HTML,CSS,PHP,Java,Javascript,Node.js,SQL

Posted 09 February 2011 - 10:08 AM (#17)

View PostKoen, on 09 February 2011 - 08:59 AM, said:

I wanted to as well :P

He reported a russian spammer here -- I just happened to see the misspelling at the same time ;-)

View Postgibbonweb, on 09 February 2011 - 09:20 AM, said:

So, um, if its deprecated... what's the new thingy then?

Maybe deprecated wasn't the right word... local databases were removed from the HTML5 draft spec entirely. It's just deprecated in all current browsers that still have LocalDB implemented.

Although, the advanced key/val store is still part of the HTML5 spec. It's no local SQL, but it can be pretty powerful and is much more convenient than using cookies to do the same thing.
0


User is offline gibbonweb 

  • 兄ヨハネス
  • Group: Members
  • Posts: 1615
  • Joined: 23-June 10
  • LocationMunich(DE)
  • Expertise:HTML,CSS,PHP,Javascript,Python,SQL,Graphics

Posted 09 February 2011 - 10:20 AM (#18)

View PostKyek, on 09 February 2011 - 10:08 AM, said:


Maybe deprecated wasn't the right word... local databases were removed from the HTML5 draft spec entirely. It's just deprecated in all current browsers that still have LocalDB implemented.

Although, the advanced key/val store is still part of the HTML5 spec. It's no local SQL, but it can be pretty powerful and is much more convenient than using cookies to do the same thing.

So they let developers play around for a while and then went "oh I guess we'll just drop that, go play somewhere else"? hmpf.
caution: may contain irony.
NOTE that quality posts can only be guaranteed if a +rep advance payment has been made.
gibbonweb | github | hdr photography

Posted Image
0


User is online Kyek 

  • Founder of wdR
  • Group: Administrators
  • Posts: 4834
  • Joined: 20-February 10
  • LocationPhiladelphia, PA, USA
  • Expertise:HTML,CSS,PHP,Java,Javascript,Node.js,SQL

Posted 09 February 2011 - 10:33 AM (#19)

View Postgibbonweb, on 09 February 2011 - 10:20 AM, said:

So they let developers play around for a while and then went "oh I guess we'll just drop that, go play somewhere else"? hmpf.

They had a good reason-- well, a reason they thought was good, anyway ;-). Their spec outlined EXACTLY what SQLite is, and said browsers should implement that spec. Then the spec writers got upset when every single one of the browsers solved this problem by implementing SQLite. They said that in order for the specification to have control over how the technology works, it needs to remain independent from any currently-built piece of software. Which makes sense, but designing a spec that matches an extremely popular and well-written library and then expecting everyone NOT to use that library is more than a little ridiculous. They'd exercised such excellent foresight up to that point.
0


User is offline Koen 

  • Leroy Jenkins
  • Group: Members
  • Posts: 2409
  • Joined: 10-March 10
  • Locationthe Netherlands
  • Expertise:HTML,CSS,Javascript,Graphics

Posted 09 February 2011 - 11:55 AM (#20)

View PostKyek, on 09 February 2011 - 10:08 AM, said:

He reported a russian spammer here -- I just happened to see the misspelling at the same time ;-)

I know, I was on my iPod and couldn't report it.
Twitter: @KoenKlaren
0


Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

3 User(s) are reading this topic
0 members, 3 guests, 0 anonymous users


Enter your sign in name and password


Sign in options
  Or sign in with these services