HTML5本地存储之Database Storage篇[2]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML5本地存储之Database Storage篇[2]</title>
    <style>  
        .addDiv{  
            border: 2px dashed #ccc;  
            width:400px;  
            text-align:center;  
        }  
        th {  
            font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;  
            color: #4f6b72;  
            border-right: 1px solid #C1DAD7;  
            border-bottom: 1px solid #C1DAD7;  
            border-top: 1px solid #C1DAD7;  
            letter-spacing: 2px;  
            text-transform: uppercase;  
            text-align: left;  
            padding: 6px 6px 6px 12px;  
        }  
        td {  
            border-right: 1px solid #C9DAD7;  
            border-bottom: 1px solid #C9DAD7;  
            background: #fff;  
            padding: 6px 6px 6px 12px;  
            color: #4f6b72;  
        }  
    </style>  
</head>
<body onload="loadAll()">
    <!-- 
    先介绍三个核心方法

    1、openDatabase:这个方法使用现有数据库或创建新数据库创建数据库对象。

    2、transaction:这个方法允许我们根据情况控制事务提交或回滚。

    3、executeSql:这个方法用于执行真实的SQL查询。
     -->
    <button type="button" onclick="CreateDB()">CreateDB</button>
    <button type="button" onclick="CreateTable()">CreateTable</button>
    <br/><br/><br/>
    <div class="addDiv">     
        <label for="user_name">姓名:</label>  
        <input type="text" id="user_name" name="user_name" class="text"/>  
        <br/>  
        <label for="mobilephone">手机:</label>  
        <input type="text" id="mobilephone" name="mobilephone"/>  
        <br/>  
        <label for="mobilephone">公司:</label>  
        <input type="text" id="company" name="company"/>  
        <br/>  
        <input type="button" onclick="save()" value="新增记录"/>  
    </div>  
    <br/>  

    <div id="list">  
    </div> 

</body>
</html>
<script>

    // 解释一下openDatabase方法打开一个已经存在的数据库,如果数据库不存在,它还可以创建数据库。几个参数意义分别是:
    // 1,数据库名称。
    // 2,版本号 目前为1.0,不管他,写死就OK。
    // 3,对数据库的描述。
    // 4,设置数据的大小。
    // 5,回调函数(可省略)。
    // 初次调用时创建数据库,以后就是建立连接了。
    // 创建的数据库就存在本地,路径如下:
    // C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\databases\http_localhost_* 。
    // 创建的是一个sqllite数据库,可以用SQLiteSpy打开文件,可以看到里面的数据。SQLiteSpy是一个绿色软件,可以百度一下下载地址或SQLiteSpy
    // 官方下载:SQLiteSpy  http://wikitaxi.org/delphi/lib/exe/fetch.php?hash=046523&media=http%3A%2F%2Fwww.yunqa.de%2Fdelphi%2Fdownloads%2FSQLiteSpy_1.9.1.zip。
    var DB = openDatabase("student", "", "学生表", 204800, function () { });
    function CreateDB(){
        if (!DB) {
            alert("数据库创建失败!");
        } else {
            dataBase=DB;
            alert("数据库创建成功!");
        }
    }

    // executeSql函数有四个参数,其意义分别是:
    // 1)表示查询的字符串,使用的SQL语言是SQLite 3.6.19。(必选)
    // 2)插入到查询中问号所在处的字符串数据。(可选)
    // 3)成功时执行的回调函数。返回两个参数:tx和执行的结果。(可选)
    // 4)一个失败时执行的回调函数。返回两个参数:tx和失败的错误信息。(可选)
    function CreateTable(){
        dataBase.transaction( function(tx) { 
            tx.executeSql(
                "create table if not exists stu (id REAL UNIQUE, name TEXT)", 
                [], 
                function(tx,result){ alert('创建stu表成功'); }, 
                function(tx, error){ alert('创建stu表失败:' + error.message); }
            );
        });
    }

    //打开数据库  
    var db = openDatabase('contactdb','','local database demo',204800);  

    //保存数据  
    function save(){  
        var user_name = document.getElementById("user_name").value;  
        var mobilephone = document.getElementById("mobilephone").value;  
        var company = document.getElementById("company").value;  
        //创建时间  
        var time = new Date().getTime();  
        db.transaction(function(tx){  
            tx.executeSql('insert into contact values(?,?,?,?)',[user_name,mobilephone,company,time],onSuccess,onError);  
        });  
    }  
     //sql语句执行成功后执行的回调函数  
    function onSuccess(tx,rs){  
        alert("操作成功");  
        loadAll();  
    }  
    //sql语句执行失败后执行的回调函数  
    function onError(tx,error){  
        alert("操作失败,失败信息:"+ error.message);  
    }  


    //将所有存储在sqlLite数据库中的联系人全部取出来  
    function loadAll(){  
        var list = document.getElementById("list");  
        db.transaction(function(tx){  
            //如果数据表不存在,则创建数据表  
            tx.executeSql('create table if not exists contact(name text,phone text,company text,createtime INTEGER)',[]);  
            //查询所有联系人记录  
            tx.executeSql('select * from contact',[],function(tx,rs){  
               if(rs.rows.length>0){  
                    var result = "<table>";  
                    result += "<tr><th>序号</th><th>姓名</th><th>手机</th><th>公司</th><th>添加时间</th><th>操作</th></tr>";  
                    for(var i=0;i<rs.rows.length;i++){  
                        var row = rs.rows.item(i);  
                        //转换时间,并格式化输出  
                        var time = new Date();  
                        time.setTime(row.createtime);  
                        var timeStr = time.format("yyyy-MM-dd hh:mm:ss");  
                        //拼装一个表格的行节点  
                        result += "<tr><td>"+(i+1)+"</td><td>"+row.name+"</td><td>"+row.phone+"</td><td>"+row.company+"</td><td>"+timeStr+"</td><td><input type='button' value='删除' onclick='del("+row.phone+")'/><input type='button' value='修改' onclick='update(2,2)'></td></tr>";  
                    }  
                    list.innerHTML = result;  
               }else{  
                    list.innerHTML = "目前数据为空,赶紧开始加入联系人吧";  
               }   
            });  
        });  
    }


    //删除联系人信息  
    function del(phone){
         db.transaction(function(tx){  
            // 'drop table contact' 删除数据表
            //注意这里需要显示的将传入的参数phone转变为字符串类型  
            tx.executeSql('delete from contact where phone=?',[String(phone)],onSuccess,onError);  
        });  
    }  

    // 修改
    function update(id,name){
        db.transaction(function(tx){
            tx.executeSql(
                'update contact set phone=? where rowid=2',
                ['2222222222222222222222'],
                onSuccess,
                onError
            );
        });
    }

    // 时间格式化输出
    Date.prototype.format = function(format)  
    {  
        var o = {  
        "M+" : this.getMonth()+1, //month  
        "d+" : this.getDate(),    //day  
        "h+" : this.getHours(),   //hour  
        "m+" : this.getMinutes(), //minute  
        "s+" : this.getSeconds(), //second  
        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter  
        "S" : this.getMilliseconds() //millisecond  
        }  
        if(/(y+)/.test(format)) format=format.replace(RegExp.$1,  
        (this.getFullYear()+"").substr(4 - RegExp.$1.length));  
        for(var k in o)if(new RegExp("("+ k +")").test(format))  
        format = format.replace(RegExp.$1,  
        RegExp.$1.length==1 ? o[k] :  
        ("00"+ o[k]).substr((""+ o[k]).length));  
        return format;  
    }

</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值