In fact, in addition to sessionStorage and localStorage, HTML5 also supports local data storage through a local database. HTML5 uses a file-type database such as SQLLite, which is mostly concentrated on embedded devices, if you are familiar with IOSAndroid development, you should be familiar with SQLLite databases. In the previous HTML5 local Storage Web Storage, you briefly introduced how to use localStorage to implement local Storage. In fact, in addition to sessionStorage and localStorage, HTML5 also supports local data storage through local databases. HTML5 adopts the "SQLLite" file-type database, which is mostly concentrated on embedded devices, those familiar with IOS/Android development should be familiar with SQLLite databases.
The database operations in HTML5 are relatively simple, mainly including the following two functions:
1. Create an object to access the database through the openDatabase Method
The Code is as follows:
Var db = openDatabase (databasename, version, description, size)
This method has four parameters for the following functions:
Databasename: Database Name;
Version: indicates the database version. This parameter is optional;
Description: Database description;
Size: the size of the space allocated to the database;
2. Use the Database Access Object (such as db) created in step 1 to execute the transaction method for transaction processing.
The Code is as follows:
Db. transaction (function (tx )){
// Execute the database access statement
});
The transaction method uses a callback function as a parameter. In this function, perform specific operations to access the database;
3. Execute the query using the executeSql Method
The Code is as follows:
Tx.exe cuteSql (sqlQuery, [value1, value2..], dataHandler, errorHandler)
The executeSql method has the following four parameters:
SqlQuery: the SQL statement that needs to be executed. It can be create, select, update, or delete;
[Value1, value2...]: an array of all the parameters used in an SQL statement. In the executeSql method, use "?" to specify the parameters used in an SQL statement. Replace, and put these parameters in the second array in sequence;
DataHandler: The call callback function is used to obtain the query result set;
ErrorHandler: the callback function called when the execution fails;
This article uses HTML5 database support to re-implement Address Book Management in the previous article. The functions to be implemented are as follows:
You can create a contact and save it to the database. The contact fields include name, mobile phone number, company, and creation time;
Lists all currently saved contact information;
You can delete specific contact information;
Similarly, first prepare an HTML page, as shown below::
The Code is as follows:
Local Database of HTML5 Local Storage
Name:
Mobile phone:
Company:
The interface is shown as follows:
To create a new contact and store it in the database, you need the following simple JavaScript code:
The Code is as follows:
// Open the database
Var db = openDatabase ('contactdb', '', 'local database demo', 204800 );
// Save data
Function save (){
Var user_name = document. getElementById ("user_name"). value;
Var mobilephone = document. getElementById ("mobilephone"). value;
Var company = document. getElementById ("company"). value;
// Creation Time
Var time = new Date (). getTime ();
Db. transaction (function (tx ){
Tx.exe cuteSql ('insert into contact values (?,?,?,?) ', [User_name, mobilephone, company, time], onSuccess, onError );
});
}
// The callback function executed after the SQL statement is executed successfully
Function onSuccess (tx, rs ){
Alert ("operation successful ");
LoadAll ();
}
// The callback function executed when the SQL statement fails to be executed
Function onError (tx, error ){
Alert ("operation failed, failure message:" + error. message );
}
To display the list of all existing contacts, you can use the following JS Code:
The Code is as follows:
// Retrieve all contacts stored in the sqlLite Database
Function loadAll (){
Var list = document. getElementById ("list ");
Db. transaction (function (tx ){
// If the data table does not exist, create a data table
Tx.exe cuteSql ('create table if not exists contact (name text, phone text, company text, createtime INTEGER) ', []);
// Query all contact records
Tx.exe cuteSql ('select * from contact ', [], function (tx, rs ){
If (rs. rows. length> 0 ){
Var result ="
For details about the format function that involves formatting time, refer to the following JS implementation.
Date. prototype. format = function (format)
{
Var o = {
"M +": this. getMonth () + 1, // month
"D +": this. getDate (), // day
"H +": this. getHours (), // hour
"M +": this. getMinutes (), // minute
"S +": this. getSeconds (), // second
"Q +": Math. floor (this. getMonth () + 3)/3), // quarter
"S": this. getMilliseconds () // millisecond
}
If (/(y +)/. test (format) format = format. replace (RegExp. $1,
(This. getFullYear () + ""). substr (4-RegExp. $1. length ));
For (var k in o) if (new RegExp ("(" + k + ")"). test (format ))
Format = format. replace (RegExp. $1,
RegExp. $1. length = 1? O [k]:
("00" + o [k]). substr ("" + o [k]). length ));
Return format;
}
To implement a specific contact, you need to execute the following JS Code
// Delete the contact information
Function del (phone ){
Db. transaction (function (tx ){
// Note that the phone parameter to be displayed here is converted to the string type.
Tx.exe cuteSql ('delete from contact where phone =? ', [String (phone)], onSuccess, onError );
});
}
For more information about Table Styles, see the following CSS code.
Th {
Font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
Color: #4f6b72;
Border-right: 1px solid # C1DAD7;
Border-bottom: 1px solid # C1DAD7;
Border-top: 1px solid # C1DAD7;
Letter-spacing: 2px;
Text-transform: uppercase;
Text-align: left;
Padding: 6px 6px 6px 12px;
}
Td {
Border-right: 1px solid # C9DAD7;
Border-bottom: 1px solid # C9DAD7;
Background: # fff;
Padding: 6px 6px 6px 12px;
Color: #4f6b72;
}
";Result + ="
Serial number |
Name |
Mobile phone |
Company |
Time added |
Operation |
";For (var I = 0; IVar row = rs. rows. item (I );// Convert the time and format the output.Var time = new Date ();Time. setTime (row. createtime );Var timeStr = time. format ("yyyy-MM-dd hh: mm: ss ");// Assemble the row nodes of a tableResult + ="
"+ (I + 1) +" |
"+ Row. name +" |
"+ Row. phone +" |
"+ Row. company +" |
"+ TimeStr +" |
|
";}List. innerHTML = result;} Else {List. innerHTML = "the current data is empty. Please join the contact ";}});});}: The Code is as follows:Finally, the interface implementation is as follows: : The Code is as follows:: The Code is as follows: