本文介绍: /tx 是一个SQLTransaction对象,后面的所有操作基于对象。// 实例调用方法,接收一个回调函数。// 返回数据库实例
<!DOCTYPE html&gt;
<html lang="en"&gt;

<head&gt;
    <meta charset="UTF-8"&gt;
    <meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    <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>

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注