This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

preface

During the development of Web applications, some data storage requirements will be designed. Common storage methods may include: Saving login cookies; LocalStorage and SessionStorage using the browser’s LocalStorage; WebSQL and IndexedDB involved in persistent storage scheme of client data; Directly stored on the local file system, etc.

Previous articles to see:

Cookies for data storage | more on the challenge in August

IndexedDB for the data store

This chapter focuses on the core methods and examples of Web SQL.


WebSQL

Web SQL is a database API introduced by HTML5, which is a set of API methods for manipulating client databases using SQL statements. If you are familiar with SQL syntax, it will be easy to understand Web SQL.


How to use

Web SQL consists of three core methods: openDatabase(), Transaction (), and executeSql(). To operate on a database, you first need to open or create a database object using the openDatabase() method. This method takes five parameters, in order: The database name, version number, description text, database size, and the callback method after the database is created. The last parameter can also be default. By default, it will go to the local query whether the database has been created, if not, create a new database.

const web_db = openDatabase('web_db'.'1.0'.'Test WebSQL DB'.1024*1024)
Copy the code

When you have a database object, you can call the transaction() method to transactionally manipulate the database. This method takes a transaction function as an argument, and contains several executeSql() methods to executeSql statements. The following example is to create a table named LOGS and insert a piece of data:

// Create a log table in the web_db database
web_db.transacti0on(tx= > {
  tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log, time)')
  tx.executeSql('INSERT INTO LOGS (id, log, time) VALUES (1, 'hello world', 1628087366562).)})Copy the code

The executeSql() method receives four parameters, which are the SQL statement string to be executed, string data where the question mark (?) is inserted into the SQL query statement, and a callback after the statement is executed successfully and a callback after the statement fails. The following is an example of the code:

// Add a data piece to the STU table
web_db.transaction(tx= > {
  tx.executeSql('INSERT INTO STU (id, name) VALUES (? ,?) ',
    [id, 'Jack'].() = > console.log('Data added successfully'),
    (tx, err) = > console.error('Failed to add data', err.message)
  )
})
Copy the code

conclusion

These are the core methods and examples of WebSQL. For simple string data, you can use LocalStorage and SessionStorage, and for complex relational data, you can use Web SQl.