HTML5 local database details
For complex databases, HTML5 uses a local database for operations. This is a browser-side database. In the local database, we can directly create a database using JavaScript and execute related database operations using SQL statements. The following describes the APIs of the local database and their usage methods.
1. Use openDatabase to create a database
We can use the openDatabase method to create a database. The openDatabase method passes five parameters: Database Name, database version number (which can be omitted), description of the Database, size of the allocated database, and callback function.
To create a local database, run the following code:
var myWebDatabase = openDatabase(“user”, ”1.0”, “user info”, 1024*1024, function(){});
In this way, a user information table is created. Then, you can verify whether the created local database is successful:
if(!dataBase){alert(“The database has been created successfully!”);}else{alert(“The database has not been successfully created.”)}if(!dataBase){alert(“The database has been created successfully!”);}else{alert(“The database has not been successfully created.”)}
2. Execute SQL statements using the executeSql Method
With the executeSql method, we can directly execute normal SQL statements, as follows:
Context.exe cuteSql ('insertintotesttable (id, name) VALUES (1, "Martin ")');
Of course, this only shows the functions of executeSql, and does not explain exactly how to use and use the executeSql method. To use this method, you must introduce transaction.
3. Use transaction to process transactions,
This method is used to process transactions. Three parameters can be passed: A method containing the transaction content, a successful callback function, and a failed callback function (the latter two can be omitted ).
Combined with transaction and executeSql, we can add and create data tables to the database we created earlier. The Code is as follows:
myWebDatabase.transaction(function (context) { context.executeSql('CREATE TABLE IF NOT EXISTS testTable (id unique, name)'); context.executeSql('INSERT INTO testTable (id, name) VALUES (0, "Byron")'); context.executeSql('INSERT INTO testTable (id, name) VALUES (1, "Casper")'); context.executeSql('INSERT INTO testTable (id, name) VALUES (2, "Frank")'); });
The meaning of SQL statements is not explained much, but here we can clearly see how to create a database data table and add data in a local database.