local database
Although HTML5 has provided powerful localStorage and sessionStorage, both of them can only provide data for storing simple data structures, and are powerless for complex web application data. What's amazing is that HTML5 provides a browser-side database support, allowing us to create a local database on the browser side directly through the JS API, and supports standard SQL CRUD operations, making offline web applications more convenient to store structures. ized data. Next, we will introduce the relevant APIs and usage of local data.
The most basic steps to operate a local database are:
The first step: openDatabase method: Create an object to access the database.
Second step: Use the database access object created in the first step to execute the transaction method. Through this method, you can set an event response method to start the transaction successfully. In the event response method, you can execute SQL.
Step 3: Execute the query through the executeSql method. Of course, the query can be: CRUD.
Next, we will introduce the parameters and usage of the relevant methods.
1. openDatabase method
//Demo: Get or create a database. If the database does not exist, create it.
var dataBase = openDatabase("student", "1.0", "学生表", 1024 * 1024, function () { });
The openDatabase method opens an existing database. If If the database does not exist, it can also create the database. The meanings of several parameters are:
Database name.
The version number of the database. Currently, 1.0 is enough. Of course, you don’t need to fill it in;
-
Description of the database.
#Set the size of the allocated database (unit is kb).
Callback function (can be omitted).
#Create the database when calling for the first time, and then establish the connection.
2. The db.transaction method
can set a callback function. This function can accept a parameter that is the object of the transaction we started. SQL scripts can then be executed through this object.
3. The executeSql method executes the query
ts.executeSql(sqlQuery,[value1,value2..],dataHandler,errorHandler)
Parameter description:
qlQuery: The sql statement that needs to be executed specifically can be create, select, update, delete;
##[value1,value2..]: An array of all parameters used in the sql statement. In the executeSql method, first replace the parameters to be used in the s> statement with "?", and then form an array of these parameters and place them in the second parameter;
dataHandler: The callback function is called when the execution is successful, through which the query result set can be obtained;
errorHandler: callback function called when execution fails;