Web SQL 的使用

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="content"></div>
    <script>
        // 返回数据库的实例
        var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024)
        // 实例上调用方法,接收一个回调函数
        db.transaction(function (tx) {
            //tx 是一个SQLTransaction对象,后面的所有操作都基于该对象。
            //创建表格
            tx.executeSql('CREATE TABLE IF NOT EXISTS STU(stuId unique,stuName)')
            //插入字段
            tx.executeSql(`INSERT INTO STU(stuId,stuName) values(111,222`)
            tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
            tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
            tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
            tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
            tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
            tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
            tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
            tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
        })
        // 查询
        db.transaction(function (tx) {
            tx.executeSql('SELECT * FROM STU', [], function (tx, result) {
                console.log(result.rows) //拿到数据
                msg = `<p>查询到的数据条数一共有:${result.rows.length}条</p>`
                content.innerHTML += msg
                for (var i = 0; i < result.rows.length; i++) {
                    msg = `<p><b>${result.rows.item(i).stuName}</b></p>`
                    content.innerHTML += msg
                }
            }, null)
        })

        // 删除数据
        db.transaction(function (tx) {
            tx.executeSql('DELETE FROM STU WHERE stuId=?', [111])
        })

        // 修改数据
        db.transaction(function (tx) {
            tx.executeSql('UPDATE STU SET stuName=? WHERE stuId=2', ["寒冰"])
        })
	 </script>
</body>

</html>
相关推荐
li35744 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj4 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel4 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel5 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
西陵6 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld6 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
东风西巷8 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求
萌萌哒草头将军8 小时前
10个 ES2025 新特性速览!🚀🚀🚀
前端·javascript·vue.js
半夏陌离8 小时前
SQL 入门指南:排序与分页查询(ORDER BY 多字段排序、LIMIT 分页实战)
java·前端·数据库