HTML5 Web SQL 数据库 讲解及使用

为什么页面刷新后表就没了?openDatabase是什么?openDatabase是浏览器提供的吗?

Web SQL 是在浏览器上模拟数据库,可以使用 JS 来操作 SQL 完成对数据的读写。

Web SQL 数据库 API 并不是 HTML5 规范的一部分,但是它是一个独立的规范,引入了一组使用 SQL 操作客户端数据库的 APIs。

Web SQL 数据库可以在最新版的 Safari, Chrome 和 Opera 浏览器中工作。

核心方法

以下是规范中定义的三个核心方法:

  1. openDatabase:这个方法使用现有的数据库或者新建的数据库创建一个数据库对象。
  2. transaction:这个方法让我们能够控制一个事务,以及基于这种情况执行提交或者回滚。
  3. executeSql:这个方法用于执行实际的 SQL 查询。
db = {};

created(){
    // 页面每次加载 调用 初始化
    this.handleCreateSql();
},

methods:{

// 初始化
handleCreateSql(){
    /* 
    * openDatabase 作用:
    * 初始化 web SQL 对象
    * after.. 可打开已创建过的 web SQL 数据库表
    * after.. 可用于创建新的 web SQL 数据库表
    */
    this.db = openDatabase(
        `zu_db`,
        "1.0",
        `我创建的db`,
        2 * 1024 * 1024,
        ()=>{}
    );
    /* 
    * 依次解析:
    * 1.数据库名称
    * 2.数据库版本号 (随便填写就行)
    * 3.数据库描述 (随便填写就行)
    * 4.数据库大小  (正常这个就够用了,不够用自己改一下就行)
    * 5.回调函数 (不必须,这个回调函数本人试过,貌似不好用-_-) 所以猜测应该是初始化
    * 失败后回调用的)
    */
    
    // transaction 控制提交或回滚
    // CREATE TABLE IF NOT EXISTS 不存在就创建,存在就不创建
    this.db.transaction(function(tx) {
        tx.executeSql(
        "CREATE TABLE IF NOT EXISTS T_TABLE (id, name, age, createDate)"
        );
    });
},

/* 
* executeSql 提供了四个参数:
* 1.字符串的SQL语句 (必须)
* 2.对应SQL语句中的问号参数,使用[]传入 (不必须)
* 3.成功时的回调函数 函数中的返回参数分别是 (tx,results) (不必须)
* 4.失败时的回调函数 函数中的返回参数分别是 (tx,results) (不必须,results对象内
* 提供失败信息)
*/

// 取表id最大的数据
async getMaxId(){
    const result = await new Promise((resolve) =>
        this.db.transaction(function(tx) {
            let id = 0;
            tx.executeSql("SELECT * FROM T_TABLE where id=(select max(id) FROM T_TABLE)",
            [], 
            (tx, results) => {
                if(results.rows.length > 0){
                    id = results.rows[0].id;
                }
                resolve(id + 1)
            });
        })
    );
    return result;
},

// 添加数据
async handleAddSql(){
    const id = await this.getMaxId()
    const the = this;

    this.db.transaction(function(tx) {
        tx.executeSql(
        "INSERT INTO T_TABLE (id, name, age, createDate) values (?, ?, ?, ?)",
        [id, the.sql.name, the.sql.age, '2022-02-28'],
        (tx, results) =>{
            console.log('追加成功')
        });
    });
},

// 检索数据
this.db.transaction(function(tx) {
    tx.executeSql("SELECT * FROM T_TABLE", [], function(tx, results) {
        console.log('results =>',results.rows)
    });
});

// 修改数据
handleUpdateSql(){
    const the = this;
    this.db.transaction(function(tx) {
    tx.executeSql("UPDATE T_TABLE set name = ? , age = ? where id = ?", 
        [the.sql.name, the.sql.age, the.sql.id], 
        (tx, results) => {
            console.log('修改成功')
        });
    })
},

// 删除表
handleDropSql(){
    this.db.transaction(function(tx) {
        tx.executeSql("drop table T_TABLE", [], (tx, results) => {
            console.log('删除成功')
        });
    })
},

}

控制台查看 webSQL

猜你喜欢

转载自blog.csdn.net/weixin_43221910/article/details/123138119