search
HomeWeb Front-endH5 TutorialHTML5 local storage-detailed explanation of the basic use of IndexedDB

In HTML5 Local Storage - Web SQL Database mentioned that Web SQL Database has actually been abandoned, and the local storage supported by HTML5 has actually become

Web Storage (Local Storage and Session Storage) with IndexedDB. Web Storage uses simple string key-value pairs to store data locally, which is convenient and flexible, but cannot store large amounts of structured data. IndexedDB is an API that can store large amounts of structured data on the client and use indexes for efficient retrieval.

Asynchronous API

Most operations in IndexedDB are not our commonly used calling methods and return result modes, but the request-response mode, such as the operation of opening a database

var request=window.indexedDB.open('testDB');

This command does not return a handle to the DB object. What we get is an IDBOpenDBRequest object, and the DB object we want to get is in its result attribute,

HTML5 local storage-detailed explanation of the basic use of IndexedDB

The response requested by this command is an IDBDatabase object, which is the IndexedDB object,

HTML5 local storage-detailed explanation of the basic use of IndexedDB

In addition to result, IDBOpenDBRequest interface Several important attributes are defined

  • onerror: callback function handle for failed request

  • onsuccess: callback function handle for successful request

  • onupgradeneeded: Request database version change handle

The so-called asynchronous API means that not after this instruction is executed, we can use request.result to obtain indexedDB Object, just like using ajax, completion of statement execution does not mean that the object has been obtained, so we usually handle it in its callback function.

Create database

The statement just now has shown how to open an indexedDB database. You can create or open an indexedDB by calling the indexedDB.open method. See a complete process

function openDB (name) {            
var request=window.indexedDB.open(name);
            request.onerror=function(e){
                console.log('OPen Error!');
            };
            request.onsuccess=function(e){
                myDB.db=e.target.result;
            };
        }        var myDB={
            name:'test',
            version:1,
            db:null
        };
        openDB(myDB.name);

A myDB object is defined in the code. In the successful destruction function of creating indexedDB request, the DB object obtained by the request is assigned to the db attribute of myDB, so that myDB can be used. .db to access the created indexedDB.

version

We noticed that in addition to onerror and onsuccess, IDBOpenDBRequest also has a similar callback function handle - onupgradeneeded. This handle is called when the version number of the database we request to open is inconsistent with the version number of the existing database.

The indexedDB.open() method also has a second optional parameter, the database version number. When the database is created, the default version number is 1. When the version number we pass in is inconsistent with the current version number of the database, onupgradeneeded will be called. Of course, we cannot try to open a version lower than the current database version, otherwise onerror will be called. Modify the example just now

function openDB (name,version) {            
var version=version || 1;            
var request=window.indexedDB.open(name,version);
            request.onerror=function(e){
                console.log(e.currentTarget.error.message);
            };
            request.onsuccess=function(e){
                myDB.db=e.target.result;
            };
            request.onupgradeneeded=function(e){
                console.log('DB version changed to '+version);
            };
        }        var myDB={
            name:'test',
            version:3,
            db:null
        };
        openDB(myDB.name,myDB.version);

Since a database with version 1 has just been created, open the version When it is 3, it will output on the console: DB version changed to 3

Close and delete the database

To close the database, you can directly call the close method of the database object

function closeDB(db){
            db.close();
        }

Delete The database uses the deleteDatabase method of the indexedDB object

function deleteDB(name){
            indexedDB.deleteDatabase(name);
        }

Simple call

var myDB={
            name:'test',
            version:3,
            db:null
        };
        openDB(myDB.name,myDB.version);
        setTimeout(function(){
            closeDB(myDB.db);
            deleteDB(myDB.name);
        },500);

Due to the asynchronous API, there is no guarantee that the db object can be obtained before the closeDB method is called (actually obtaining the db object is faster than executing a statement much slower), so I used setTimeout to delay it. Of course, we noticed that each indexedDB instance has an onclose callback function handle, which is used to process when the database is closed. Interested students can try it. The principle is very simple and will not be demonstrated.

object store

After having a database, we naturally want to create a table to store data, but there is no concept of table in indexedDB, but objectStore, a database Can contain multiple objectStore, objectStore is a flexible data structure that can store multiple types of data. In other words, an objectStore is equivalent to a table, and each piece of data stored in it is associated with a key.

We can use a specified field in each record as the key value (keyPath), or we can use an automatically generated incrementing number as the key value (keyGenerator), or we can not specify it. Depending on the type of selection key, the data structures that objectStore can store are also different

键类型 存储数据
不使用 任意值,但是没添加一条数据的时候需要指定键参数
keyPath Javascript对象,对象必须有一属性作为键值
keyGenerator 任意值
都使用 Javascript对象,如果对象中有keyPath指定的属性则不生成新的键值,如果没有自动生成递增键值,填充keyPath指定属性


事务

在对新数据库做任何事情之前,需要开始一个事务。事务中需要指定该事务跨越哪些object store。

事务具有三种模式

  1. 只读:read,不能修改数据库数据,可以并发执行

  2. 读写:readwrite,可以进行读写操作

  3. 版本变更:verionchange

var transaction=db.transaction([students','taecher']);  //打开一个事务,使用students 和teacher object store
var objectStore=transaction.objectStore('students'); //获取students object store

给object store添加数据

调用数据库实例的createObjectStore方法可以创建object store,方法有两个参数:store name和键类型。调用store的add方法添加数据。有了上面知识,我们可以向object store内添加数据了

keyPath

因为对新数据的操作都需要在transaction中进行,而transaction又要求指定object store,所以我们只能在创建数据库的时候初始化object store以供后面使用,这正是onupgradeneeded的一个重要作用,修改一下之前代码

function openDB (name,version) {            
var version=version || 1;            

var request=window.indexedDB.open(name,version);
            request.onerror=function(e){
                console.log(e.currentTarget.error.message);
            };
            request.onsuccess=function(e){
                myDB.db=e.target.result;
            };
            request.onupgradeneeded=function(e){                
            var db=e.target.result;                
            if(!db.objectStoreNames.contains('students')){
                    db.createObjectStore('students',{keyPath:"id"});
                }
                console.log('DB version changed to '+version);
            };
        }

这样在创建数据库的时候我们就为其添加了一个名为students的object store,准备一些数据以供添加

var students=[{ 
            id:1001, 
            name:"Byron", 
            age:24 
        },{ 
            id:1002, 
            name:"Frank", 
            age:30 
        },{ 
            id:1003, 
            name:"Aaron", 
            age:26 
        }];
function addData(db,storeName){            
var transaction=db.transaction(storeName,'readwrite'); 
            var store=transaction.objectStore(storeName); 

            for(var i=0;i<students.length;i++){
                store.add(students[i]);
            }
        }


openDB(myDB.name,myDB.version);
        setTimeout(function(){
            addData(myDB.db,&#39;students&#39;);
        },1000);

这样我们就在students object store里添加了三条记录,以id为键,在chrome控制台看看效果

HTML5 local storage-detailed explanation of the basic use of IndexedDB

keyGenerate

function openDB (name,version) {            
var version=version || 1;            
var request=window.indexedDB.open(name,version);
            request.onerror=function(e){
                console.log(e.currentTarget.error.message);
            };
            request.onsuccess=function(e){
                myDB.db=e.target.result;
            };
            request.onupgradeneeded=function(e){                
            var db=e.target.result;                
            if(!db.objectStoreNames.contains(&#39;students&#39;)){
                    db.createObjectStore(&#39;students&#39;,{autoIncrement: true});
                }
                console.log(&#39;DB version changed to &#39;+version);
            };
        }

HTML5 local storage-detailed explanation of the basic use of IndexedDB

剩下的两种方式有兴趣同学可以自己摸索一下了

查找数据

可以调用object store的get方法通过键获取数据,以使用keyPath做键为例

function getDataByKey(db,storeName,value){            
var transaction=db.transaction(storeName,&#39;readwrite&#39;); 
            var store=transaction.objectStore(storeName); 
            var request=store.get(value); 
            request.onsuccess=function(e){ 
                var student=e.target.result; 
                console.log(student.name); 
            };
}

更新数据

可以调用object store的put方法更新数据,会自动替换键值相同的记录,达到更新目的,没有相同的则添加,以使用keyPath做键为例

function updateDataByKey(db,storeName,value){            var transaction=db.transaction(storeName,&#39;readwrite&#39;); 
            var store=transaction.objectStore(storeName); 
            var request=store.get(value); 
            request.onsuccess=function(e){ 
                var student=e.target.result; 
                student.age=35;
                store.put(student); 
            };
}

删除数据及object store

调用object store的delete方法根据键值删除记录

function deleteDataByKey(db,storeName,value){            
var transaction=db.transaction(storeName,&#39;readwrite&#39;); 
            var store=transaction.objectStore(storeName); 
            store.delete(value); 
        }

调用object store的clear方法可以清空object store

function clearObjectStore(db,storeName){            
var transaction=db.transaction(storeName,&#39;readwrite&#39;); 
            var store=transaction.objectStore(storeName); 
            store.clear();
}

调用数据库实例的deleteObjectStore方法可以删除一个object store,这个就得在onupgradeneeded里面调用了

if(db.objectStoreNames.contains(&#39;students&#39;)){ 
                    db.deleteObjectStore(&#39;students&#39;); 
}

最后

这就是关于indexedDB的基本使用方式,很多同学看了会觉得很鸡肋,和我们正常自己定义个对象使用没什么区别,也就是能保存在本地罢了,这是因为我们还没有介绍indexedDB之所以称为indexed的杀器——索引,这个才是让indexedDB大显神通的东西,下篇我们就来看看这个杀器。

The above is the detailed content of HTML5 local storage-detailed explanation of the basic use of IndexedDB. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor