Khóa học miễn phí IndexedDB – Connection nhận dự án làm có lương

IndexedDB – Connection



A database is an organized collection of structured data stored in a computer system. To perform operations on data we need to connect to a database. In this chapter, we will discuss how to create/connect to a database, open a database, and delete a database.

Creating a database − You can create a database in IndexedDB using the open() function. Following is the syntax of this function.

let openRequest = indexedDB.open(name, version);

Where,

  • name is the name of the database you need to create.
  • version is the version of the database that is to be created. The default value of this parameter is 1. If you omit this value, the version is considered as 1.

The version value you pass to this function should not be less than the current version (of the IndexedDB). This function returns 1 if the database is created successfully and it returns 0 in case of a failure.

Example

Following is the example to create a database in IndexedDB

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Indexed db</title>
</head>
<body>
   <script>
      //Creating a database
      const request = indexedDB.open("myDatabase", 1);
      if(indexedDB){
         document.write("Database Created......");
      }
   </script>
</body>
</html>

Output

If you save the above code in a file “test.html” and run it, the following message will be displayed on the browser −

Database Created......

Verification

Since IndexedDB is the browser”s built-in database you observe the created database in the browser itself.

Right-click on the resultant page, click on inspect element and select the Application tab. You can see the IndexedDB database there if you expand it you can see the created database file as shown below −

Indexeddb Files

Generating Handlers

An event is an action performed on an HTML element. Using JavaScript we can handle these events. From now on we use JavaScript handlers (to make this clearer).

If the request is a success, we use the onsuccess event.

request.onerror = event => {
   // Do something (ex: document.write("error");
};

If the request is a failure, we use onerror event.

request.onsuccess = event => {
   // Do something (ex : document.write("success");
};

When you create a database or increase the version number of an existing database we use onupgradeneeded event.

request.onupgradeneeded = event => {
   var db = event.target.result;
};

Example

Following example displays the message “database creation success”. If the database creation is successful. In here we are using the onsuccess and onerror handlers to display these messages.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Handlers</title>
</head>
<body>
   <script>
      const request = indexedDB.open("DATABASE", 1);
      request.onsuccess = function (){
         document.write("Database created successfully...")
      }
      request.onerror = function(){
         document.write("database creation error");
      }
      request.onupgradeneeded = function(event){
         var db = event.target.result;
      }
   </script>
</body>
</html>

Output

If you save the above code in a file “test.html” and run it, the following message will be displayed on the browser −

Database created successfully...

Connecting to an existing database

To interact with IndexedDB, we use JavaScript. The code we write in JavaScript doesn”t interact with databases directly. We need to connect with the database using a connection object to manipulate the objects of the database.

Opening a database directly creates a connection. There can be multiple connections to a database. When a connection is initially created it is in the open state.

You can connect to an IndexedDB database using the open() function (which we used to create a database).

Syntax

Following is the syntax to connect to an existing database.

let openRequest = indexedDB.open(name, version);

Example

A JavaScript example that interacts with an existing database using a connection object is given below −

<!DOCTYPE html>
<html lang="en">
<head>
   <title>OPENING A DATABASE</title>
</head>
<body>
   <script>
      const request = indexedDB.open("DATABASE", 1);
      request.onsuccess = function (){
         document.write("<br> Database created successfully")
      }
      const requestone = indexedDB.open("Database1",2);
      requestone.onsuccess = function(){
         document.write("<br> Database created successfully");
      }
      const requesttwo = indexedDB.open("DATABASE",1);
      requesttwo.onsuccess = function(){
         document.write("<br> Database opened successfully");
      }
   </script>
</body>
</html>

Output

The above program prints the following output on the browser −

Database created successfully 
Database opened successfully 
Database created successfully

If the request is a success, then the event named onsuccess will be called.

Another way to check databases in the browser

In addition to the inspect element, there is another way to check the IndexedDB database in the browser.

In the top right corner, there will be a customize and control button, Click it.

Select the More tools option in the list and then select Developer tools.

More Tools

On the next page select the Application tab where you can see the IndexedDB database.

Opening Database

Deleting a database

If there is an excess of any database which we do not need or it unnecessarily occupies space, we can delete it. To delete a database we can use the deleteDatabase() function.

Following is the syntax of the deleteDatabase() function −

let deleteRequest = indexedDB.deleteDatabase(name)

Here, the name parameter is the name of the database that we want to delete.

Example

Following example creates a database named TestDatabase and deletes it using the deleteDatabase() function.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Indexed db</title>
</head>
<body>
   <script> 
      const request = indexedDB.open("TestDatabase", 1);
      request.onsuccess = function () {
         document.write("Database Created Successfully");
      }; 
      var req = indexedDB.deleteDatabase("TestDatabase");
      req.onsuccess = function () {
         document.write("Database Deleted Successfully");
      };
      req.onerror = function () {
         document.write("Couldn''t delete the database");
      };
   </script>
</body>
</html>

Deleting a database Directly From the browser

Once you create a database, you can directly delete it database from the browser. To do so, follow the steps given below −

Step 1 − Open the page where you can see the IndexedDB database (storage) in the browser, using one of the following ways

  • Inspect option − Right−click → Inspect → Application or,

  • Developer tools − Customize and Control Options → More tools → Developers tools → Application

Step 2 − If you expand the IndexedDB storage, you can observe the list of databases created as shown below.

Test

Step 3 − Click on the database you want to delete. On the right−hand side, you will find the Delete Database button. If you click on it, this database will be deleted.

Delete Database

Closing a database

To close a database we need to use the function IDBDatabase.close()

Syntax

IDBDatabase.close();

The close() method of the IDBDatabase interface returns immediately and closes the connection.

The connection is not closed until all transactions are complete but, new transactions cannot be created for this connection and methods throw exceptions if the closing operation is pending.

Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc