JavaScript Local Database Storage Websql

Source: Internet
Author: User

Recently our app is not very good, because it is a problem, submit the function of the topic, before just from the app to submit the wrong problem to the server, the service side is the answer, check the right answer, return the result set, now a lot of users reflect, submission speed is very slow, many times, are submitted unsuccessful, so the leader let me put the topic , the task of verifying the problem is also given to the front end, the service side only accepts and stores the wrong problem, thereby alleviating the pressure on the service side,

In because our question bank quantity is very big, and kind of more, two sets of questions each year, a set of questions have about 100 questions, so simple localstorage and can not meet us, so we chose to use the database, the beginning, want to try Sqllit, but its own H5 standard is not recommended, Below this link, you can see Dcloud offers the app offline storage scheme, you can choose

http://ask.dcloud.net.cn/article/166

Eventually we used the Websql, and then using Websql, when we met a few pits

1. Database operation is asynchronous, sometimes very annoying, for example, I want to get 100 questions, the operation of these topics, return to the method, I did not use the callback function I used is the method of the parameter, feel used generally, sometimes, too complex operation, often problems, because after all, is the function, closure you know.

2. Database version number of the modification, the situation is really disgusting, I thought it was very simple to solve the small garbage, card the half-afternoon, I finally cooperate with localstorage to solve, God tired of a mechanism

Simply introduce:

Database every time you open, you need to have a version number, if you open the database, the incoming version number, and the data itself version number is different, then will be error, and reported the wrong thief wonderful

      

This is when I am 2.0 version of the database, modified version 1.0 when the error, the solution: every time you open the build database, all from the Localstorage, when the database version number and the local different, we need to open the database, get to the Databases object, and then modify the data Library version, database body has the native Changeversion method, used to modify the database version, and then sync to Localstorage, the next time the database is opened, directly from the localstorage inside get the latest; (^-^)

3. When inserting data, do not jump page, because it is inserted asynchronously, so it is easy to insert into a, jump page, the result is, stop the loop, do not plug in, so if there is a jump page and insert data in the same function inside the collection, try to put in the page after the jump to insert

The following paste on my operation, the package of JS file (in fact, I also find on-line, I changed according to the needs of a bit)

Websql.js

1 /**2 * Database Operations helper classes, defined objects, data manipulation methods are defined here3 */4 varDbname= ' Yearstopic ';/*Database name*/5 varDbdesc = ' real problem Bank of the year ';/*Database Description*/6 varDbsize = 20*1024*1024;/*Database Size*/7 varDataBase =NULL;/*Staging Database Objects*/8 /*table sole name in the database*/9 varwebsqltable = "Websqltable";Ten /** One * Open Database A * @returns dataBase: Open success Null: Open Failed -  */ - functionwebsqlopendb () { the     /*database has to be opened without creating*/ -    varVersion =window.localStorage.DBversion; -DataBase =window.opendatabase (dbname, version, Dbdesc, dbsize); -     if(dataBase) { +Console.log ("Database created/opened successfully!")); -}Else{ +Console.log ("Database creation/Open failed! "); A     } at     returndataBase; - } - //Modifying the database version - functionchangedatabaseversion (old_version,new_version) { -     vardb =websqlopendb (); -Db.changeversion (Old_version,new_version,NULL,function(ERR) {},NULL) inWindow.localStorage.DBversion =new_version; - } to /** + * form inside the new database - * @param tableName: Table sole name the  */ * functionwebsqlcreattable (tableName) { $ //chinaareaopendb ();Panax Notoginseng     varCreattablesql = ' CREATE TABLE IF not EXISTS ' + tablename+ ' (ID text,question text) '; -Database.transaction (function(ctx,result) { theCtx.executesql (creattablesql,[],function(ctx,result) { +Console.log ("Table creation succeeded" +tableName); A},function(TX, error) { theConsole.log (' CREATE TABLE failed: ' + tableName +error.message); +         }); -     }); $ } $ //Inserting Data - functionwebsqlinsterdatatotable (tablename,id,question) { -     varQuestion =json.stringify (question); the     varInstertablesql = ' INSERT into ' + TableName + ' VALUES (?,?) '; -Database.transaction (function(CTX) {WuyiCtx.executesql (Instertablesql,[id,question],function(ctx,result) { theConsole.log ("Insert" + tableName + ID + "Success"); -         }, Wu         function(TX, error) { -Console.log (' Insert failed: ' +error.message); About         }); $     }); - } - /** - * Get all the data from a single form in a database A * @param tableName: Table sole name + * Return Data collection the  */ - functionWebsqlgetalldata (TABLENAME,FN) { $     varSelectallsql = ' SELECT * from ' +TableName; theDatabase.transaction (function(CTX) { theCtx.executesql (selectallsql,[],function(ctx,result) { theConsole.log (' Query succeeded: ' + tableName + ' __ ' +result.rows.length); the             varLen =result.rows.length; -             varQuerydataarray = []; in              for(vari = 0;i < len;i++) { the Querydataarray.push (Json.parse (Result.rows.item (i). QUESTION)); the             } About fn (querydataarray); the         }, the         function(TX, error) { theConsole.log (' Query failed: ' +error.message); +         }); -     }); the }Bayi //query all data, get JSON format the functionWebsqlgetalldatajson (TABLENAME,FN) { the     varSelectallsql = ' SELECT * from ' +TableName; -Database.transaction (function(CTX) { -Ctx.executesql (selectallsql,[],function(ctx,result) { theConsole.log (' Query succeeded: ' + tableName + ' __ ' +result.rows.length); the             varLen =result.rows.length; the             varQuerydataarray = {}; the              for(vari = 0;i < len;i++) { -                 varID =Result.rows.item (i). ID; theid = id.replace ('. 0 ', '); theQuerydataarray[id] =Json.parse (Result.rows.item (i). QUESTION); the             }94 fn (querydataarray); the         }, the         function(TX, error) { theConsole.log (' Query failed: ' +error.message);98         }); About     }); - }101 /**102 * Get some data from a form inside a database103 * @param tableName: Table sole name104 * @param name: Name the  */106 functionWebsqlgetadata (TABLENAME,ID,FN) {107     varSelectsql = ' SELECT * from ' + tableName + ' WHERE ID =? '108Database.transaction (function(CTX) {109Ctx.executesql (selectsql,[id+ '. 0 '),function(ctx,result) { thefn && fn (json.parse (result.rows.item (0). QUESTION))111         }, the         function(TX, error) {113Console.log (' Query failed: ' +error.message); the         }); the     }); the }117 118 functionwebsqldeletetable (tabname) {119Database.transaction (function(TX) { -Tx.executesql (' DROP TABLE ' +tabname+ '); 121Console.log (' delete table ' +tabname+ ' success ')122     },123     function(tx,err) {124Console.log (' delete table ' +tabname+ ' failed ') the     })126 }127 /** - * Delete all data in the form129 * @param tableName: Table sole name the  */131 functionwebsqldeletealldatafromtable (tableName) { the     varDeletetablesql = ' DELETE from ' +TableName;133 Localstorage.removeitem (tableName);134Database.transaction (function(ctx,result) {135Ctx.executesql (deletetablesql,[],function(ctx,result) {136Console.log ("Delete table succeeded" +tableName);137},function(TX, error) {138Console.log (' Delete table failed: ' + tableName +error.message);139         }); $     });141}

Just so much, remember, add.

JavaScript Local Database Storage Websql

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.