Friday 30 August 2013

HTML5 database creation

HTML5 has some exciting features & one of them is database storage on your browser itself. In this tutorial i will guide you brief about creation of HTML5 database & start working with it. HTML5 database is created on SQLLite(open source db software) of browser .We have 3 types of ways to store data on browser :
  • localStorage , sessionStorage
  • Web SQL
  • IndexDB


Starting with localStorage 

<script>

function Save(){
  try {
      localStorage.setItem("name","ABCD");
     // can also save like this
    // localStorage["name"] = "ABCD";
     alert("data saved");
   }
  catch {  
     alert("localstorage is not supported on this browser");
  }
}

function Read(){
  alert( localStorage.getItem("name") );
}

function Delete(){
  localStorage.removeItem("name");
  // can also use below to remove all localStorage specific to url
 // localStorage.clear();
}

</script>

For sessionStorage syntax is exactly same as localStorage except for that localStorage data remains even after browser is closed whereas sessionStorage is cleared as soon as browser is closed.

Remember that all data is saved specific to url /domain & also there is limit upto which that data can be saved , yes it is more than cookies , & may be around 5MB.



Web SQL Database in HTML5



First job is to initialize database :



You can use try catch for checking if browser supports HTML5 Web SQL . Here we initialized database using openDatabase & giving necessary details like Database Name , version , description & size of database. Version here is for updating database incase you updated your schema or anything which you want to reflect on client browser.

SQL statements i am sure you already have gone through (basics).

Now executing some sql statements to save data to database table (Here : Ktables).

You can put necessary logic on error or success of sql execution.

Now , when you want to load data from database table using appropriate query :




On chrome in tools -> developer tools you can see your created database & respective values.












IndexDB Database in HTML5

Initialize IndexDB database . Here we gave name to the database & version no.(version is for when we want
to reflect change in database schema on client side). OnError & Onsuccess is for handling events.























When database version is changed (schema) . OnUpgradeneeded ,  it runs for the first time & when ever database version is changed. Here we also define which will act as index & which will not.
















Saving data on IndexDB , by creating object Person



















You can view data using browser developer tools.










Basics of Tree data structure

Tree data structure simulates a  hierarchical tree structure, with root and subtrees represented by linked nodes. Some Terminology Root...