HTML5 browser's database engine Indexdb usage Example

Source: Internet
Author: User

1,INDEXEDDB Introduction

The INDEXEDDB standard is an officially recognised local database solution for HTML5. The goal is not to replace the server-side database, which is useful in some specific scenarios:

(1) Create a self-contained offline application
For example, a page can get the required data from a server-side database when there is a network connection, and then save the data to a local database for offline access.
(2) Optimize performance
Some applications use a lot of data, and if you continue to get the same data when you need it, Web page performance will drop. Similarly, to create an application that generates data through complex computations, we can save all the required data to a INDEXEDDB database if we do not want to waste time repeating the same calculations. Make it a super custom cache.
(3) Improved local storage
To save data between browser sessions and pass between pages. If the data structure is simple and small, you can use local storage. But if the data is very large or the structure is very complex, it is much simpler and quicker to manage with the INDEXEDDB database.

2, browser support for the INDEXEDDB
(1) IE10 support
(2) Firefox 10, Chrome 23, Opera 15
(3) The latest version of the desktop version or mobile version of Safari also supports INDEXEDDB.

3, create and connect to the database

(1) Suppose we use a database to do a favorites function, where the data saved (linked objects) are as follows:


function Linkrecord (name, URL, description) {
THIS.name = name;
This.url = URL;
this.description = description;
}

(2) Create and connect the database code as follows:

var database;





Window.onload = function () {


Open Database


var request = Window.indexedDB.open ("Linksdb", 1);





request.onsuccess = function (event) {


Alert ("Create/Open Database succeeded.") ");





Make the database accessible anywhere


Database = Request.result;





Subsequent operations, such as displaying all the links saved in the database


Showlinks ();


};





Request.onerror = function (event) {


Alert ("Error occurred:" + request.error);


};





request.onupgradeneeded = function (event) {


Alert ("Create the database for the first time or update the database.") ");


Alert ("The old database version is:" + event.oldversion + "updated after the new version is:" + event.newversion)





var db = Request.result;


var objectstore = Db.createobjectstore ("Links", {keypath: "url"});


}


};

Code Description:

The 1,database variable is defined outside so that it can be accessed from anywhere in the code to facilitate subsequent additions and deletions.
2, whether you are creating a new database or opening an existing database, you are calling the Window.indexeddb object's open () function. The first parameter is the database name, and the second parameter is the version number (the new database version number is set to 1).
Everything in 3,INDEXEDDB is asynchronous, so when you call the open () method, you just send a request.
4, in order to respond when the task is complete (such as the Open () method above), we set up three event handlers: The onsuccess that handles the successful result, the onerror that handles the exception, and the processor that handles the Onupgradeneeded event.

(3) Onupgradeneeded event description
The onupgradeneeded incident was more special, so it was raised separately.
It triggers when the database version is not available (for example, the requested database version is 2 and the local current database version is 1), at which point we can upgrade the database operation, such as adding a new datasheet (Event.oldversion can get the current database version)
will also trigger when the requested database does not exist, in which case the browser will automatically create an empty database.

4, the creation of data tables
You can create a datasheet by providing only the name and keyword path of the datasheet (unlike a traditional database and defining the name and type of each field). The example above creates a data table named Links in the database, and the keyword path is the URL (the corresponding property name in this matching data object)


var db = Request.result;
var objectstore = Db.createobjectstore ("Links", {keypath: "url"});

A keyword path represents a property in an object that is the primary key (primary key), and the primary key is the information that uniquely identifies each piece of data. Because each link data has a unique URL, all can be used to do the keyword.
If there is no property in the data that clearly fits the master key, you can add an ID to act as the primary key and automatically generate a unique number each time you insert new data.


var objectstore = Db.createobjectstore ("Links", {keypath: "id", autoincrement:true});

5, delete the entire database

Window.indexedDB.deleteDatabase ("Linksdb");

6, the creation of the transaction
To do anything with INDEXEDDB, whether it is writing data or reading data, you must first create a transaction. One or more data operations that a transaction submits together as a unit. If any part of the transaction fails, all operations in the transaction are undone and the database reverts to the state before the transaction.
Call the transaction () method of the database object to create the transaction:
1
var transaction = Database.transaction (["Links"], "ReadWrite");
First parameter: A list of all the data tables that need to be introduced into this transaction. This information allows INDEXEDDB to lock the datasheet to prevent other code from overlapping or possibly inconsistent modifications.
Second parameter: A string indicating the type of transaction. If you want to create a transaction that can perform any action on the datasheet (whether inserting, updating, or deleting data), use ReadWrite, or if you only need to read the data, use ReadOnly.

7, add, modify data

Like other data operations: first, you create a transaction, then get the object store for the transaction, call an object-stored method, and handle success and error messages.


var Linkrecord = new Linkrecord ("hangge.com", "http://www.hangge.com",
"Sailing song-to be the best developer Knowledge Platform");

var transaction = Database.transaction (["Links"], "ReadWrite");
var objectstore = Transaction.objectstore ("Links");

var request = Objectstore.put (Linkrecord);
Request.onerror = function (event) {
Alert ("Error occurred:" + request.error);
};

request.onsuccess = function (event) {
Alert ("Data saved successfully");
};
If the invocation of the put () added data has the same primary key as the existing data, the browser replaces the new data with the existing data.

8, query all the data in the datasheet

We need a cursor to browse a INDEXEDDB datasheet.

var transaction = Database.transaction (["Links"], "ReadOnly");


var objectstore = Transaction.objectstore ("Links");





var request = Objectstore.opencursor ();





Request.onerror = function (event) {


Alert ("Error occurred:" + request.error);


};





Prepare a string to display the result


var message = "";





request.onsuccess = function (event) {


Create a cursor


var cursor = Event.target.result;





Determine if there is data based on the cursor


if (cursor) {


var linkrecord = Cursor.value;


Message + + Linkrecord.name + "" + Linkrecord.url + "\ n";





Call the Cursor.continue () method to access the next piece of data


When the cursor reaches the next piece of data, the Onsuccess event is triggered again


Cursor.continue ();


}


else {


If a result is not, the cursor is in the end, the output information


alert (message);


}


}

9, query a single data

It's simpler than getting all the data, and you don't need to use a cursor, just use the object store's Get () method.

var transaction = Database.transaction (["Links"], "ReadOnly");
var objectstore = Transaction.objectstore ("Links");

var request = Objectstore.get ("http://www.hangge.com");

Request.onerror = function (event) {
Alert ("Error occurred:" + request.error);
};

request.onsuccess = function (event) {
var linkrecord = Request.result;
var message = "Get data succeeded." \ n ";
Message + + Linkrecord.name + "\ n";
Message + + Linkrecord.url + "\ n";
Message + + linkrecord.description + "\ n";
alert (message);
}

10, delete a piece of data

Use the Delete () method stored by the object.


var transaction = Database.transaction (["Links"], "ReadWrite");
var objectstore = Transaction.objectstore ("Links");

var request = Objectstore.delete ("http://www.hangge.com");

Request.onerror = function (event) {
Alert ("Error occurred:" + request.error);
};

request.onsuccess = function (event) {
Alert ("Delete succeeded.") ");
}

11, complete sample

<! DOCTYPE html>


<html lang= "en" >


<head>


<meta charset= "Utf-8" >


<title>hangge.com</title>





<style>


Body {


font-family: "Trebuchet MS", Helvetica, Sans-serif;


font-size:14px;


margin-left:20px;


margin-right:20px;


}





form {


margin-bottom:30px;


}





fieldset {


margin-bottom:15px;


padding:10px;


max-width:500px;


}





Legend {


padding:0px 3px;


Font-weight:bold;


}





Label {


width:125px;


Display:inline-block;


Vertical-align:top;


margin:6px;


}





Input:focus {


Background: #eaeaea;


}





Input {


font-family: "Trebuchet MS", Helvetica, Sans-serif;


width:300px;


}





TEXTAREA {


font-family: "Trebuchet MS", Helvetica, Sans-serif;


height:100px;


width:500px;


}





Input[type=button] {


width:150px;


padding:8px;


}





Div.resultbox {


margin-top:20px;


padding:10px;


border:2px solid #D8EEFE;


border-radius:15px;


max-width:500px;


}





. LinkButton {


Cursor:pointer;


Color:blue;


Text-decoration:underline;


}


</style>


<script>


var database;





Window.onload = function () {


var request = Window.indexedDB.open ("LinksDB2", 1);





request.onsuccess = function (event) {


Alert ("Create/Open Database succeeded.") ");





Make the database accessible anywhere


Database = Request.result;





Show all the links saved in the database


Showlinks ();


};





Request.onerror = function (event) {


Alert ("Error occurred:" + request.error);


};





request.onupgradeneeded = function (event) {


Alert ("Create the database for the first time or update the database.") ");


Alert ("The old database version is:" + event.oldversion + "updated after the new version is:" + event.newversion)





var db = Request.result;


var objectstore = Db.createobjectstore ("Links", {keypath: "url"});


}


};





function Addlink () {


Get data from form forms


var name = document.getElementById ("name"). Value;


var url = document.getElementById ("url"). Value;


var description = document.getElementById ("description"). Value;





var Linkrecord = new Linkrecord (name, URL, description);





var transaction = Database.transaction (["Links"], "ReadWrite");


var objectstore = Transaction.objectstore ("Links");





var request = Objectstore.put (Linkrecord);


Request.onerror = function (event) {


Alert ("Error occurred:" + request.error);


};





request.onsuccess = function (event) {


Alert ("Add link succeeded");





Show all the links saved in the database


Showlinks ();


};


}





function Showlinks () {


var transaction = Database.transaction (["Links"], "ReadOnly");


var objectstore = Transaction.objectstore ("Links");





var request = Objectstore.opencursor ();





Request.onerror = function (event) {


Alert ("Error occurred:" + request.error);


};





The string to display on the page


var markuptoinsert = "";





request.onsuccess = function (event) {


Create a cursor


var cursor = Event.target.result;





Determine if there is data based on the cursor


if (cursor) {


var linkrecord = Cursor.value;


Markuptoinsert + + "<a href=" + Linkrecord.url + ">" + linkrecord.name + "</a> (" +


"<span class= ' LinkButton ' data-url= '" + Linkrecord.url +


"' onclick= ' getlinkdetails (This) ' > detailed </span>" + "" +


"<span class= ' LinkButton ' data-url= '" + Linkrecord.url +


"' onclick= ' Deletelink (this) ' > delete </span>" +


") <br>";





Call the Cursor.continue () method to access the next piece of data


When the cursor reaches the next piece of data, the Onsuccess event is triggered again


Cursor.continue ();


}


else {


If a result is not, the cursor is in the end, the output information


if (Markuptoinsert = = "") {


Markuptoinsert = "<< no links. >> ";


}


else {


Markuptoinsert = "<i> currently added links are as follows: </i><br>" + Markuptoinsert;


}





Display data


var resultselement = document.getElementById ("links");


resultselement.innerhtml = Markuptoinsert;





}


};


}





function Getlinkdetails (Element) {


var url = element.getattribute ("Data-url");





var transaction = Database.transaction (["Links"], "ReadOnly");


var objectstore = Transaction.objectstore ("Links");





var request = Objectstore.get (URL);





Request.onerror = function (event) {


Alert ("Error occurred:" + request.error);


};





request.onsuccess = function (event) {


Alert ("Data acquisition success");


var linkrecord = Request.result;





var resultselement = document.getElementById ("Linkdetails");


resultselement.innerhtml = "<b>" + linkrecord.name + "</b><br>" +


"<b>URL:</b>" + Linkrecord.url + "<br>" +


"<b> description:</b>" + linkrecord.description;


}


}





function Deletelink (Element) {


var url = element.getattribute ("Data-url");





var transaction = Database.transaction (["Links"], "ReadWrite");


var objectstore = Transaction.objectstore ("Links");





var request = Objectstore.delete (URL);





Request.onerror = function (event) {


Alert ("Error occurred:" + request.error);


};





request.onsuccess = function (event) {


Alert ("Delete succeeded");





Show all the links saved in the database


Showlinks ();


}


}





function Linkrecord (name, URL, description) {


THIS.name = name;


This.url = URL;


this.description = description;


}


</script>


</head>





<body>


<h1> Website Favorites </h1>


<form action= "#" >


<fieldset>


<legend> Detailed information </legend>


<label for= "name" > Name:</label>


<input id= "name" placeholder= "Some website" ><br>


<label for= "url" >url address:</label>


<input id= "url" placeholder= "http://somesite.somedomain.com" ><br>


<label for= "Description" > Description:</label>


<input id= "description" placeholder= "A site about something" ><br>


</fieldset>


<div><input type= "button" value= "New link" onclick= "Addlink ()" >


<input type= "button" value= "Show All Links" onclick= "showlinks ()" ></div>


</form>





<div class= "Resultbox" id= "Links" >


 


</div>





<div class= "Resultbox" id= "Linkdetails" >


 


</div>





</body>


</html>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.