JavaScript 进阶营让前端飞Web前端之路

HTML5 进阶系列:webSQL数据库

2018-04-23  本文已影响28人  巩小白

HTML5 Web SQL 数据库

Web SQL 数据库 API 并不是 HTML5 规范的一部分。但是它是一个独立的规范,因为安全性能等问题,官方现在也已经放弃了维护。但是,这并不影响你对他的使用,只要你的数据不涉及到安全性能问题,你大可去使用它。当然,它是基于MYSQL的,你要在学习他之前,你先的有一点mysql的知识。

核心方法

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

打开数据库

我们可以使用 openDatabase() 方法来打开已存在的数据库,如果数据库不存在,则会创建一个新的数据库,使用代码如下:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024,callback); 

openDatabase() 方法对应的五个参数说明:

transaction

transaction方法用以处理事务,当一条语句执行失败的时候,整个事务回滚。方法有三个参数

executeSql

executeSql方法用以执行SQL语句,返回结果,方法有四个参数

db.transaction(function(tx) {
    tx.executeSql("SELECT * FROM User WHERE id = ?", [id],
    (tx, res) => {
          console.log("sql成功")
    }, (tx, res) => {
          console.log("sql失败")
        });
    }, (tx, res) => {
            console.log("事务成功")
        },(tx, res) => {
            console.log("事务成功")
        }
)

完整实例

这个例子有完整的,增、删、查操作


20180423_114749 (1).gif 20180423_123205.gif 20180423_123343.gif
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            .login_wrap {
                margin: 20px auto 0;
                width: 300px;
                height: 280px;
                background: aqua;
                text-align: center;
            }
            
            .login_username, .login_password {
                height: 60px;
                display: flex;
                align-items: center;
            }
            
            input {
                height: 30px;
            }
            
            .login_button {
                width: 300px;
                height: 36px;
                line-height: 36px;
                background: red;
                cursor: pointer;
                margin-top: 20px;
            }
            
            #content {
                width: 400px;
                margin: 0 auto;
                background: aquamarine;
            }
            
            .rowClass {
                line-height: 36px;
                border: 1px solid #00FFFF;
                display: flex;
                justify-content: space-between;
            }
            
            .deleteClass {
                padding: 5px;
                background: cadetblue;
                cursor: pointer;
            }
        </style>
    </head>

    <body>
        <div class="login_wrap">
            <div class="login_username">
                <label htmlFor="">用户名</label>
                <input id="username" name="username" />
            </div>
            <div class="login_password">
                <label htmlFor="">密码</label>
                <input id="password" name="password" />
            </div>
            <div id="login_button" class="login_button">提交</div>

            <div id="deleteBtn" class="login_button">删除数据库</div>
        </div>

        <div id="content"></div>

        <script type="text/javascript">
            window.onload = function() {

                let login_button = document.getElementById("login_button");
                let deleteBtn = document.getElementById("deleteBtn");
                let content = document.getElementById("content");
                var db = openDatabase('UDB', '1.0', 'Test DB', 2 * 1024 * 1024);

                renderAllDB(db);

                db.transaction(function(tx) {
                    tx.executeSql('CREATE TABLE IF NOT EXISTS User(id INTEGER PRIMARY KEY AUTOINCREMENT,u_name VARCHAR(20),u_pwd VARCHAR(10))');
                });

                //添加数据
                login_button.onclick = function() {
                    let username = document.getElementById("username").value;
                    let passwords = document.getElementById("password").value;

                    if(username && passwords) {
                        add(db,username, passwords);
                    }
                }

                //删除全部数据
                deleteBtn.onclick = function() {
                    deleteAllFn(db);
                }

                let dataLists = content.querySelectorAll("deleteClass");

                //删除单条数据
                content.addEventListener("click",function(e){
                    var target = e.target;
                    var className = target.getAttribute("class");
                    if(className === "deleteClass"){
                        let id = target.getAttribute("data-id");
                        deleteFn(db,id);
                    }
                })
            }

            //删除单条数据
            function deleteFn(db,id) {
                db.transaction(function(tx) {
                    tx.executeSql('DELETE FROM User WHERE id in (?)', [id], (tx, res) => {}, (tx, res) => {});
                }, (tx, res) => {}, (tx, res) => {
                    renderAllDB(db);
                });
            }

            //删除全部数据
            function deleteAllFn(db) {
                db.transaction(function(tx) {
                    tx.executeSql('DELETE FROM User', [], (tx, res) => {
                        console.log("deletesssss", tx, res)
                    }, () => {
                        console.log("deletesssss1111111111111111")
                    });
                }, (tx) => {
                    console.log("22222222222222", tx)
                }, (tx) => {
                    renderAllDB(db);
                });
            }

            //添加数据
            function add(db, username, passwords) {
                db.transaction(function(tx) {
                    tx.executeSql('INSERT INTO User (u_name, u_pwd) VALUES (?,?)', [username, passwords],
                        function(tx, results) {
                            renderDB(db, results.insertId, username, passwords)
                        },
                        function(tx, res) {
                            console.log(tx, res.message)
                        })
                }, (tx) => {
                    console.log("22222222222222", tx)
                }, (tx) => {
                    console.log("1111111111111111")
                });
            }

            //读取数据
            function renderAllDB(db) {
                db.transaction(function(tx) {
                    tx.executeSql("SELECT * FROM User", [],
                        (tx, res) => {
                            let str = "";
                            let data = res.rows;

                            for(item of data) {
                                str += `<p class="rowClass">姓名:${item.u_name}</span>密码:<span>${item.u_pwd}</span><span class="deleteClass" data-id= "${item.id}">删除</span></p>`
                            }

                            content.innerHTML = str;

                        }, (tx, res) => {
                            console.log("9999", res)
                        });
                });
            }

            //读取数据
            function renderDB(db, id, username, passwords) {
                db.transaction(function(tx) {
                    tx.executeSql("SELECT * FROM User WHERE id = ?", [id],
                        (tx, res) => {
                            content.innerHTML += `<p class="rowClass">姓名:${username}</span>密码:<span>${passwords}</span><span data-id= "${id}" class="deleteClass">删除</span></p>`
                        }, (tx, res) => {});
                });
            }
        </script>
    </body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读