HTML5 local Storage-Database Storage

Source: Internet
Author: User

HTML5 local Storage-Database Storage

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

. Code
  1. 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;

      Share the best UI front-end framework!
    • 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;

      . Code
      1. Db. transaction (function (tx )){
      2. // Execute the database access statement
      3. });

        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

        . Code
        1. 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, prepare an HTML page as follows:

              Share the best UI front-end framework !. Code
              1. Local Database of HTML5 Local Storage
              2. Name:

              3. Mobile phone:

              4. Company:


              5. The interface is shown as follows:


                To create a new contact and store it in the database, you need the following simple JavaScript code:

                . Code
                1. // Open the database
                2. Var db = openDatabase ('contactdb', '', 'local database demo', 204800 );
                3. // Save data
                4. Function save (){
                5. Var user_name = document. getElementById ("user_name"). value;
                6. Var mobilephone = document. getElementById ("mobilephone"). value;
                7. Var company = document. getElementById ("company"). value;
                8. // Creation Time
                9. Var time = new Date (). getTime ();
                10. Db. transaction (function (tx ){
                11. Tx.exe cuteSql ('insert into contact values (?,?,?,?) ', [User_name, mobilephone, company, time], onSuccess, onError );
                12. });
                13. }
                14. // The callback function executed after the SQL statement is executed successfully
                15. Function onSuccess (tx, rs ){
                16. Alert ("operation successful ");
                17. LoadAll ();
                18. }
                19. // The callback function executed when the SQL statement fails to be executed
                20. Function onError (tx, error ){
                21. Alert ("operation failed, failure message:" + error. message );
                22. }

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

                  Share the best UI front-end framework !. Code
                  1. // Retrieve all contacts stored in the sqlLite Database
                  2. Function loadAll (){
                  3. Var list = document. getElementById ("list ");
                  4. Db. transaction (function (tx ){
                  5. // If the data table does not exist, create a data table
                  6. Tx.exe cuteSql ('create table if not exists contact (name text, phone text, company text, createtime INTEGER) ', []);
                  7. // Query all contact records
                  8. Tx.exe cuteSql ('select * from contact ', [], function (tx, rs ){
                  9. If (rs. rows. length> 0 ){
                  10. Var result ="
                  11. Result + ="
                  12. For (var I = 0; I Var row = rs. rows. item (I );
                  13. }
                  14. // Convert the time and format the output.
                  15. Var time = new Date ();
                  16. Time. setTime (row. createtime );
                  17. Var timeStr = time. format ("yyyy-MM-dd hh: mm: ss ");
                  18. // Assemble the row nodes of a table
                  19. Result + ="
                  20. List. innerHTML = result;
                  21. } Else {
                  22. List. innerHTML = "the current data is empty. Please join the contact ";
                  23. }
                  24. });
                  25. });
                  26. }

                    For the format function that involves formatting time, see the following JS implementation:

                    . Code
                    1. Date. prototype. format = function (format)
                    2. {
                    3. Var o = {
                    4. "M +": this. getMonth () + 1, // month
                    5. "D +": this. getDate (), // day
                    6. "H +": this. getHours (), // hour
                    7. "M +": this. getMinutes (), // minute
                    8. "S +": this. getSeconds (), // second
                    9. "Q +": Math. floor (this. getMonth () + 3)/3), // quarter
                    10. "S": this. getMilliseconds () // millisecond
                    11. }
                    12. If (/(y +)/. test (format) format = format. replace (RegExp. $1,
                    13. (This. getFullYear () + ""). substr (4-RegExp. $1. length ));
                    14. For (var k in o) if (new RegExp ("(" + k + ")"). test (format ))
                    15. Format = format. replace (RegExp. $1,
                    16. RegExp. $1. length = 1? O [k]:
                    17. ("00" + o [k]). substr ("" + o [k]). length ));
                    18. Return format;
                    19. }

                      Finally, the interface implementation is as follows:

                      Share the best UI front-end framework!


                      To implement a specific contact, you need to execute the following JS Code:

                      . Code
                      1. // Delete the contact information
                      2. Function del (phone ){
                      3. Db. transaction (function (tx ){
                      4. // Note that the phone parameter to be displayed here is converted to the string type.
                      5. Tx.exe cuteSql ('delete from contact where phone =? ', [String (phone)], onSuccess, onError );
                      6. });
                      7. }

                        For more information about Table Styles, see the following CSS code:

                        Share the best UI front-end framework !. Code
                        1. Th {
                        2. Font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
                        3. Color: #4f6b72;
                        4. Border-right: 1px solid # C1DAD7;
                        5. Border-bottom: 1px solid # C1DAD7;
                        6. Border-top: 1px solid # C1DAD7;
                        7. Letter-spacing: 2px;
                        8. Text-transform: uppercase;
                        9. Text-align: left;
                        10. Padding: 6px 6px 6px 12px;
                        11. }
                        12. Td {
                        13. Border-right: 1px solid # C9DAD7;
                        14. Border-bottom: 1px solid # C9DAD7;
                        15. Background: # fff;
                        16. Padding: 6px 6px 6px 12px;
                        17. Color: #4f6b72;
                        18. }

                  27. "; "; ";
                    Serial number Name Mobile phone Company Time added Operation
                    "+ (I + 1) +" "+ Row. name +" "+ Row. phone +" "+ Row. company +" "+ TimeStr +"
Related Article

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.