Introduction
Nowadays you have heard of HTML5 web storage to store data locally within the user's browser. If you are not familiar with it then I am giving you a very quick introduction to it.
HTML Web Storage: when we want to store data at the client's machine we usually use cookies but HTML5 introduces the new concept called web storage that does the same thing with more security and efficiency. By using this we can store a large amount of data without affecting your website performance because this data is not included with every call to the server.
HTML5 introduces the following two mechanisms
Now we can explain what localDB.js is. It is a library that maps the structure of databases in objects using the localStorage API provided by HTML5. So it is compatible with all browsers that support HTML5 Web Storage. This is completely standalone and there is no dependency except browser supporting localStorage.
There is no driver required, just add the library and use it. This library is useful for web applications, mobile apps or game engines. It has a limit of 5MB before the browser warns the user.
How To Use/Install?
Download from
https://github.com/mike183/localDB
And import the library
- <script type="text/javascript" src="localdb.min.js"></script>
Structure of Database
The structure of the dabase is displayed below.
Load a database
The following will create a new database if the database is not present, otherwise, it loads the existing database.
- var db=new localdb(<Database Name>);
Create Table
The following will create a schemaless table, so there is no need to provide column information; simply use "g=" to provide the name of the table and it will create the table.
- Db.createTable('table_name');
Delete a Table
You can delete a table by simply calling dropTable method as in the following:
- Db.dropTable('table name');
Insert Data
A localDB database is schemaless so when you insert data there is no need to worry about the number of columns that you have provided in another row because each row can have its own set of columns.
Db.insert('table_name',data object);
Updating database
- Db.update(table_name,data_object,where_object);
- Db.updateById(table_name,data_object,id);
Checking for the existence of a database or table
- Var res=db.tableExists('table_name');
- Var res=db.tableExists('users');
Exporting Database
- Var json=db.exportData();
- Var json=db.exportData('table_name');
So that is all about the boring syntax. We will now create a sample application to understand the real use of this library.
Conclusion
There are many libraries present for storing data in a database using the localStorage API of HTML5. Here I have introduced one of them, so if you want to explore more please go through other libraries. It is really powerful since we can store data at the client-side more securely and efficiently.