HTML5 local storage-database storage

Source: Internet
Author: User
Tags add time

In the previous article web storage of HTML5 local storage, we briefly introduced how to use localstorage to implement local storage. In fact, apart from sessionstorage and localstorage, HTML5 also supports local data storage through a local database. HTML5 uses a file-type database such as "SQLite", which is mostly concentrated on embedded devices and familiar with IOS/Android development, be familiar with SQLite 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

 
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;

 
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

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 re-implements the previous article through HTML5 Database SupportArticleAddress Book Management in. 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, prepare an HTML page as follows:

 
    
    local database of HTML5 local storage     
  
  
Name:
mobile phone:
companies:

The interface is shown as follows:


To create a new contact and store it to the database, the following simple JSCode:

// Open the database var DB = opendatabase ('contactdb', '', 'local database demo', 204800); // Save the 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);}) ;}// callback function onsuccess (TX, RS) executed after the SQL statement is executed successfully) {alert ("operation succeeded"); loadall () ;}// callback function onerror (TX, error) {alert ("operation failed, failure Information: "+ error. message );}

To display the list of all existing contacts, you can use the following JS Code:

// Obtain 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 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 = "<Table> "; result + = "<tr> <TH> NO. </Th> <TH> name </Th> <TH> mobile phone </Th> <TH> company </Th> <th> Add time </Th> <TH> operation </Th> </tr> "; for (VAR I = 0; I <Rs. rows. length; I ++) {var 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 "); // result + = "<tr> <TD>" + (I + 1) + "</TD> <TD>" + row. name + "</TD> <TD>" + row. phone + "</TD> <TD>" + row. company + "</TD> <TD>" + timestr + "</TD> <input type = 'button 'value = 'Delete 'onclick = 'del (" + row. phone + ") '/> </TD> </tr>";} List. innerhtml = result;} else {list. innerhtml = "the current data is empty. Join the contact now ";}});});}

For the format function that involves formatting time, see 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 ;}

Finally, the interface implementation is as follows:


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 needs to be displayed here is changed 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 12px; color: #4f6b72 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.