search
HomeWeb Front-endH5 TutorialDetailed explanation of HTML5 local database instance

Web SQL Databases of HTML5 (html5 local database) are indeed very tempting. When you find that you can use the same query statement as mysql query to operate the local database, you will find this thing quite interesting. Today, let’s learn about HTML 5’s Web SQL Database API: openDatabase, transaction, executeSql. The Web SQL Database API is not actually part of the HTML5 specification, but a separate specification. It manipulates the client's database through a set of APIs. Mainstream browsers such as Safari, Chrome, Firefox, and Opera already support Web SQL Database. HTML5's Web SQL Databases are indeed very tempting. When you find that you can use the same query statement as a mysql query to operate a local database, you will find this thing quite interesting. Today, let’s learn about HTML 5’s Web SQL Database API.
The following will introduce one by one how to create and open a database, create a table, add data, update data, delete data, and delete a table.
First introduce the three core methods
1. openDatabase: This method uses an existing database or creates a new databaseCreate a databaseObject.
2. Transaction: This method allows us to control transaction submission or rollback according to the situation.
3. executeSql: This method is used to execute real SQL queries.
Step one: Open the connection and create the database

The code is as follows:

var dataBase = openDatabase("student", "1.0", "学生表", 1024 * 1024, function () { });
if
 (!dataBase) {
    alert("数据库创建失败!");
} 
else
 {
    alert("数据库创建成功!");
}

Explain the openDatabase method to open an existing database. If the database Doesn't exist, it can also create a database. The meanings of several parameters are:
1, database name.
2. The version number is currently 1.0. Leave it alone and just write it to death.
3, description of the database.
4, set the data size.
5, Callback function (can be omitted).
Create the database when calling for the first time, and then establish the connection.
The created database exists locally, and the path is as follows:
C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\databases\http_localhost_4987.
What is created is a sqllite database. You can use SQLiteSpy to open the file and see the data inside. SQLiteSpy is a green software. You can download it from Baidu or the official SQLiteSpy download address: SQLiteSpy.
Step 2: Create a data table

The code is as follows:

this.createTable=function() {  
dataBase.transaction( function(tx) {     
tx.executeSql(        
"create table if not exists stu (id REAL UNIQUE, name TEXT)",         
[],         
function(tx,result){ alert('创建stu表成功'); 
},         
function(tx, error){ alert('创建stu表失败:' + error.message);     
}); 
});
}

Explain,
executeSql function has four parameters, their meanings are:
1) Represents the string of the query, and the SQL language used is SQLite 3.6.19.
2) Insert the string data where the question mark is in the query.
3) Callback function executed when successful. Returns two parameters: tx and the result of execution.
4) A callback function executed when failure occurs. Returns two parameters: tx and failure error message.
Step 3: Perform add, delete, modify and query
1) Add data:

The code is as follows:

this.insert = function () {
  dataBase.transaction(function (tx) {
            tx.executeSql(
        "insert  into  stu (id, name) values(?, ?)",
        [id, '徐明祥'],
        function () { alert('添加数据成功'); },
        function (tx, error) { alert('添加数据失败: ' + error.message); 
        } );
    });

2) Query data

The code is as follows:

this.query = function () {
  dataBase.transaction(function (tx) {
            tx.executeSql(
        "select  *  from  stu", [],
         function (tx, result) {  //执行成功的回调函数
             //在这里对result 做你想要做的事情吧...........
            },
         function (tx, error) {
            alert('查询失败: ' + error.message);
         } );
      });
}

Explain it
The callback function that executes successfully in the above code has a parameter result.

result: The queried data set. Its data type is SQLResultSet, just like the DataTable in C#.
SQLResultSet is defined as:

The code is as follows:

interface  SQLResultSet {
             readonly  attribute  long  insertId;
             readonly  attribute  long  rowsAffected;
             readonly  attribute  SQLResultSetRow
List
  rows;
             };

The most important property—rows of SQLResultSetRowList type is the "rows" of the data set.
rows has two attributes: length, item.
So, get the value of a certain row and column of the query result: result.rows[i].item[fieldname].

3) Update data

The code is as follows:

this.update = function (id, name) {   
dataBase.transaction(function (tx) {            
tx.executeSql(        
"update  stu  set  name =  ?  where  id= ?",        
[name, id],         
function (tx, result) {         },        
function (tx, error) {            
alert('更新失败: ' + error.message);        
});   
});
}

4)Delete data

The code is as follows:

this.del = function (id) {
     dataBase.transaction(function (tx) {
            tx.executeSql(
        "
delete
  from  stu  where  id= ?",
        [id],
         function (tx, result) {
         },
        function (tx, error) {
            alert('删除失败: ' + error.message);
        });
    });
}

5 )Delete the data table

The code is as follows:

this.dropTable = function () {    
dataBase.transaction(function (tx) {            
tx.executeSql('drop  table  stu');     
});
}

[Related recommendations]

1. Html5 free video tutorial

2. H5 code demonstration for making a timer

3. H5 detailed example of completing multiple image uploads

4. Detailed explanation of H5’s custom attribute data-*

5. Teach you how to implement an H5 micro-scene

The above is the detailed content of Detailed explanation of HTML5 local database instance. 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
Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.