Database Storage for HTML5 local Storage, html5storage

Source: Internet
Author: User
Tags add time

Database Storage for HTML5 local Storage, html5storage

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. <! Doctype html>
  2. <Html>
  3. <Head>
  4. <Meta charset = "UTF-8"/>
  5. <Title> local database for HTML5 local storage </title>
  6. <Style>
  7. . AddDiv {
  8. Border: 2px dashed # ccc;
  9. Width: 400px;
  10. Text-align: center;
  11. }
  12. </Style>
  13. </Head>
  14. <Body onload = "loadAll ()">
  15. <Div class = "addDiv">
  16. <Label for = "user_name"> name: </label>
  17. <Input type = "text" id = "user_name" name = "user_name" class = "text"/>
  18. <Br/>
  19. <Label for = "mobilephone"> mobile phone: </label>
  20. <Input type = "text" id = "mobilephone" name = "mobilephone"/>
  21. <Br/>
  22. <Label for = "mobilephone"> company: </label>
  23. <Input type = "text" id = "company" name = "company"/>
  24. <Br/>
  25. <Input type = "button" onclick = "save ()" value = "add record"/>
  26. </Div>
  27. <Br/>
  28. <Div id = "list">
  29. </Div>
  30. </Body>
  31. </Html>

 

 

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 = "<table> ";
  11. Result + = "<tr> <th> NO. </th> <th> name </th> <th> mobile phone </th> <th> company </th> <th> Add time </th> <th> operation </th> </tr> ";
  12. For (var I = 0; I <rs. rows. length; I ++ ){
  13. Var row = rs. rows. item (I );
  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 + = "<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> ";
  20. }
  21. List. innerHTML = result;
  22. } Else {
  23. List. innerHTML = "the current data is empty. Please join the contact ";
  24. }
  25. });
  26. });
  27. }

 

 

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. }

Where is the data stored in HTML5 local storage?

The basic usage is as follows: localStorage. name = "k1w1"; in this way, a database on your local disk stores the data. I could not accept the data written to my local disk and could not find its exact location. So I found that Chrome is stored in the form of sqlite database files. In C: \ Users \ Username \ AppData \ Local \ Google \ Chrome \ User Data \ Default \ Local Storage, although the suffix is. localstorege is actually a database file of sqlite. You can open it with sqlite and see the data in it. I want to delete some junk data generated when I learned to use local storage. Just like I used to delete cookies. Firefox is not found at the moment. It feels like sqlite database files are encrypted (in this case, firefox is more secure ), however, every time I turn firefox off, it will automatically delete all browsing data, so I do not want to find out where it exists.

For local storage of html5 LocalStorage

The following are the storage methods of the five browsers localStorage:

In addition to BASE64 encryption (BASE64 can also be easily decrypted), other browsers use Plaintext to store data.
Therefore, we recommend that you do not use localStorage to store sensitive information, which may be encrypted.

For more information, see HTML5 local storage security analysis.
Blog.csdn.net /...


 

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.