IndexedDB is a JavaScript-based object-oriented database for client-side storage of significant amounts of structured data. IndexedDB uses indexes for high-performance data searches. While Local Storage is useful for storing small amounts of data in the form of simple key/value pairs, it is less useful for storing large amounts of structured data.
IndexedDB uses the concept of collections of JSON objects similar to NoSQL databases (MongoDB or CouchDB) and is embeded inside browser. Operations performed using IndexedDB are done asynchronously, so as not to block applications. The storage limits of indexedDB differs from browser to browser.
IndexedDB lets us store, retrieve, update and delete objects that are indexed with a key. Simple CRUD operations performed on indexedDB are explained in detail below:
Following are the basic steps to insert data in indexedDb.
STEP 1 : Check if indexedDB is supported
STEP 2 : Open a database connection
indexedDB.open method is used to open connection to a new database or an existing one. If the database name specified already exists, it will open connection to the existing database otherwise it will create a new database with the specified name and open connection to it.
The first parameter passed to open( ) method is database name and the second parameter is database version. Database version allows us to represent our current Database schema. Whenever there is a change in our DB schema, we need to upgrade the database version. To upgrade our database version, we will only need to create/delete a few object stores.
STEP 3 : Create object stores in the opened database
When we increase the version of our database (i.e load a version of database that is higher than the previously loaded version) or a webpage is hit for the first time on user’s web browser, onupgradeneeded event is triggered. This is the reason why we need to create our object stores inside onupgradeneeded event. This is the first event that is called on database connection, so it's ideal to create object stores here and then later on we can add data to these store objects.
onsuccess event is triggered when the result of a request is successfully returned which in this case would be, successfully opening the database connection. Since onupgradeneeded event is called before onsuccess event, at this point we already have object stores in our database so we will run transactions on object stores inside onsuccess event. onerror event will only be triggered if there some error occurs.
STEPS 4 - 5 : Start transaction & add objects to object stores
The first thing we need to do to add objects to an object store, is start a transaction in the database on an object store with readwrite permission. After starting transaction, we need to access our object store and add objects to it.
Now let us sum up the above steps and write complete code to insert data in indexedDB.
Following are the basic steps to update data in indexedDb.
Following are the basic steps to delete data from indexedDb.
Fetching a single record from indexedDB is performed using get( ) method already used above (in update data in indexedDB). To fetch all records in an object store, we can retrieve an object store and then use a cursor to iterate all objects in an object store.
Following are the basic steps to select data from indexedDb.
IndexedDB uses the concept of collections of JSON objects similar to NoSQL databases (MongoDB or CouchDB) and is embeded inside browser. Operations performed using IndexedDB are done asynchronously, so as not to block applications. The storage limits of indexedDB differs from browser to browser.
CRUD Operations in IndexedDB
Insert data in indexedDB
Following are the basic steps to insert data in indexedDb.
- Check if indexedDB is supported by the browser.
- Open a database connection.
- Create object stores in the opened database.
- Start a transaction on an object store with readwrite permission.
- Add objects to the object store.
STEP 1 : Check if indexedDB is supported
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB
|| window.msIndexedDB;
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.");
}
STEP 2 : Open a database connection
indexedDB.open method is used to open connection to a new database or an existing one. If the database name specified already exists, it will open connection to the existing database otherwise it will create a new database with the specified name and open connection to it.
var connection = window.indexedDB.open("Library", 1);
The first parameter passed to open( ) method is database name and the second parameter is database version. Database version allows us to represent our current Database schema. Whenever there is a change in our DB schema, we need to upgrade the database version. To upgrade our database version, we will only need to create/delete a few object stores.
STEP 3 : Create object stores in the opened database
When we increase the version of our database (i.e load a version of database that is higher than the previously loaded version) or a webpage is hit for the first time on user’s web browser, onupgradeneeded event is triggered. This is the reason why we need to create our object stores inside onupgradeneeded event. This is the first event that is called on database connection, so it's ideal to create object stores here and then later on we can add data to these store objects.
onsuccess event is triggered when the result of a request is successfully returned which in this case would be, successfully opening the database connection. Since onupgradeneeded event is called before onsuccess event, at this point we already have object stores in our database so we will run transactions on object stores inside onsuccess event. onerror event will only be triggered if there some error occurs.
var db;
connection.onerror = function(obj){
console.log("Error opening DB", obj);
}
connection.onupgradeneeded = function(obj){
console.log("Upgrading");
db = obj.target.result;
var objectStore = db.createObjectStore("books", { keyPath : "id" });
};
connection.onsuccess = function(obj){
console.log("Success opening DB");
db = obj.target.result;
}
STEPS 4 - 5 : Start transaction & add objects to object stores
The first thing we need to do to add objects to an object store, is start a transaction in the database on an object store with readwrite permission. After starting transaction, we need to access our object store and add objects to it.
var transaction = db.transaction(["books"],"readwrite");
transaction.oncomplete = function(obj) {
console.log("Success");
};
transaction.onerror = function(obj) {
console.log("Error");
};
var objectStore = transaction.objectStore("books");
objectStore.add({id: '01BBCG6789PP', name: 'A Song of Ice and Fire'});
Now let us sum up the above steps and write complete code to insert data in indexedDB.
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.");
}else{
var db;
var connection = window.indexedDB.open("Library", 1);
connection.onerror = function(obj){
console.log("Error opening DB", obj);
}
connection.onupgradeneeded = function(obj){
db = obj.target.result;
var objectStore = db.createObjectStore("books", { keyPath : "id" });
};
connection.onsuccess = function(obj){
db = obj.target.result;
addRecords();
}
function addRecords(){
var transaction = db.transaction(["books"],"readwrite");
var objectStore = transaction.objectStore("books");
objectStore.add({id: '01BBCG6789PP', name: 'A Song of Ice and Fire'});
objectStore.add({id: '908GHJTR908SS', name: 'The Lord of Rings'});
transaction.oncomplete = function(obj) {
console.log("Transaction Successful.");
};
transaction.onerror = function(obj) {
console.log("Error In Transaction.");
};
}
}
Update data in indexedDB
Following are the basic steps to update data in indexedDb.
- Check if indexedDB is supported by the browser.
- Open a database connection.
- Start a transaction on an object store with readwrite permission.
- Get the object from the object store.
- Perform changes to the object.
- Put the object back in the object store.
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.");
}else{
var db;
var connection = window.indexedDB.open("Library", 1);
connection.onerror = function(obj){
console.log("Error opening DB", obj);
}
connection.onsuccess = function(obj){
db = obj.target.result;
updateRecords();
}
function updateRecords(){
var transaction = db.transaction(["books"],"readwrite");
var objectStore = transaction.objectStore("books");
var request = objectStore.get("01BBCG6789PP");
request.onsuccess = function(event){
request.result.name = 'Harry Potter';
objectStore.put(request.result);
};
transaction.oncomplete = function(obj) {
console.log("Transaction Successful.");
};
transaction.onerror = function(obj) {
console.log("Error In Transaction.");
};
}
}
Delete data from indexedDB
Following are the basic steps to delete data from indexedDb.
- Check if indexedDB is supported by the browser.
- Open a database connection.
- Start a transaction on an object store with readwrite permission.
- Delete an object from object store.
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.");
}else{
var db;
var connection = window.indexedDB.open("Library", 1);
connection.onerror = function(obj){
console.log("Error opening DB", obj);
}
connection.onsuccess = function(obj){
db = obj.target.result;
deleteRecords();
}
function deleteRecords(){
var transaction = db.transaction(["books"],"readwrite");
var objectStore = transaction.objectStore("books");
var request = objectStore.delete("01BBCG6789PP");
request.onsuccess = function(obj){
console.log('Record Deleted');
};
request.onerror = function(obj){
console.log('Error Deleting Record');
};
transaction.oncomplete = function(obj) {
console.log("Transaction Successful.");
};
transaction.onerror = function(obj) {
console.log("Error In Transaction.");
};
}
}
Select data from indexedDB
Fetching a single record from indexedDB is performed using get( ) method already used above (in update data in indexedDB). To fetch all records in an object store, we can retrieve an object store and then use a cursor to iterate all objects in an object store.
Following are the basic steps to select data from indexedDb.
- Check if indexedDB is supported by the browser.
- Open a database connection.
- Start a transaction on an object store with readonly permission.
- Retrieve an object store.
- Use a cusor to iterate objects in an object store.
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.");
}else{
var db;
var connection = window.indexedDB.open("Library", 1);
connection.onerror = function(obj){
console.log("Error opening DB", obj);
}
connection.onsuccess = function(obj){
db = obj.target.result;
selectRecords();
}
function selectRecords(){
var transaction = db.transaction(["books"],"readonly");
var objectStore = transaction.objectStore("books");
var request = objectStore.openCursor();
request.onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
console.log(cursor.value);
cursor.continue();
} else {
console.log('No more records found.');
}
};
transaction.oncomplete = function(obj) {
console.log("Transaction Successful.");
};
transaction.onerror = function(obj) {
console.log("Error In Transaction.");
};
}
}
No comments:
Post a Comment