Foreword
Web SQL Database API is not part of the HTML5 spec, but it is a separate specification, introduced a set of APIs to use SQL operation client database. Web SQL Database can work in the latest version of Safari, Chrome and Opera browser.
The core method
The following are the core of the method defined in the specification:
- openDatabase : This method creates a database object using an existing database or create a new database.
- Transaction : This method allows us to control a transaction, and based on this case commit or rollback.
- executeSql : This method is used to perform the actual SQL query.
Open / New Database
To open an existing database by openDatabase () method, if the database does not exist, a new database will be created:
// 新建 demo 数据库
var DB = openDatabase('demo','1.0','演示',2 * 1024 * 1024)
openDatabase () corresponding to the method described five parameters:
- Name database
- version number
- Description text
- Database Size
- Create a callback
The fifth parameter, create a callback will be called after the database is created.
Create a database table
() Function created by database.transaction:
// 创建数据库 demo
var DB = openDatabase('demo','1.0','演示',2 * 1024 * 1024)
// 创建数据库表 DEMO
DB.transaction(function(TX){
TX.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, log)')
})
Insert data
NewDB a new table, and insert two records:
// 创建数据库
var DB = openDatabase('demo','1.0','演示',2 * 1024 * 1024)
// 创建数据库表
DB.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS NewDB (id unique, log)');
tx.executeSql('INSERT INTO NewDB (id, log) VALUES (1, "第一条")');
tx.executeSql('INSERT INTO NewDB (id, log) VALUES (2, "第二条")');
});
Of course, it can be dynamically added.