重新加载页面时数据库不存在。需要帮助

时间:2012-10-17 07:30:31

标签: database html5 reload indexeddb

使用HTML5代码,我创建了以下数据库,可以在数据库上创建,添加,删除和打印操作。 但是,每次加载html页面时都会创建ObjectStore,并且当我重新加载页面时,存储的其他值不存在。代码有什么问题?请帮忙。感谢。

 <html>
    <title>
    IndexedDB</title>
    <script type="text/javascript">
    var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB;
    var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
    var db;
    //var test;
    var dbVersion = 1;

    (function () {

    var Cust_Data = [{name: "ABC", email: "abc@gmail.com"}, 
                    {name: "XYZ", email: "xyz@gmail.com"}];

    function initializeDB(){
            alert("At initialize DB function");
            var request = indexedDB.open("Customers",dbVersion);

            request.onerror = function(event){
                write("Database cannot be opened:" + event.target.errorCode);
            };

            request.onsuccess = function(event){
                db = event.target.result;
                if (db.setVersion) {
                    if (db.version != dbVersion) {
                        var req = db.setVersion(dbVersion);
                        req.onerror = db.onerror;
                        req.onsuccess = function () {
                            if(db.objectStoreNames.contains("CustDetails")) {
                                alert("CustDetails store already present!");
                            }
                            else{
                            //alert("Initialize else function");
                            var objectStore = db.createObjectStore("CustDetails",{ Keypath: "AadharNumber", autoIncrement: true });
                            objectStore.createIndex("name", "name",{unique: false});
                            objectStore.createIndex("email", "email",{unique: true});

                            for(i in Cust_Data){
                                objectStore.add(Cust_Data[i]);
                            }
                            }
                        };
                    }
                    else{
                        alert("Not created ObjectStore");   
                    }
                }
            };
    }       

    function contentLoaded(){
        alert("At contentLoaded function");
        initializeDB();
        //db = initializeDB();
        //db = test.indexedDB.db;
        alert("Value of db in contentLoaded function is :" + db);
        var btnAdd = document.getElementById("btnAdd");
        var btnDelete = document.getElementById("btnDelete");
        var btnPrint = document.getElementById("btnPrint");

        btnAdd.addEventListener("click", function(){
                alert("At add function");
                //alert("Value of db in add function is :" + db);
                var name = document.getElementById("txtName").value;
                var email = document.getElementById("txtEmail").value;
                var transaction = db.transaction("CustDetails",IDBTransaction.READ_WRITE);
                //alert("Transaction statement passed");
                var objectStore = transaction.objectStore("CustDetails");
                var request = objectStore.add({name: name, email: email});
                request.onsuccess = function(event){
                alert ( "Added to the database");
                document.getElementById("txtName").value = "";
                document.getElementById("txtEmail").value = "";
            };

        },false);

        btnDelete.addEventListener("click", function(){
            //alert("At Delete function");
            //var AadharNumber = document.getElementById("AadharNumber").value;
            var AadharNumber =  parseInt(document.getElementById("AadharNumber").value);
            var transaction = db.transaction("CustDetails",IDBTransaction.READ_WRITE);
            var objectStore = transaction.objectStore("CustDetails");
            var request = objectStore.delete(AadharNumber);
            request.onsuccess = function(event){
                alert( "Aadhar Number: "+ AadharNumber + " deleted from the database");
            };

        },false);

        btnPrint.addEventListener("click", function () {
                        var output = document.getElementById("printOutput");
                        output.textContent = "";
                        var transaction = db.transaction("CustDetails", IDBTransaction.READ_WRITE);
                        var objectStore = transaction.objectStore("CustDetails");
                        var request = objectStore.openCursor();
                        request.onsuccess = function(event) {  
                            var cursor = event.target.result;  
                            if (cursor) {  
                                output.textContent += "Aadhar Number: " + cursor.key + " is " + cursor.value.name + "";
                                cursor.continue();  

                            }  
                            else {  
                                console.log("No more entries!");  
                            }  
                        };  
                    }, false); 
    }

    window.addEventListener("DOMContentLoaded", contentLoaded, false); 
    }
    )();

    </script>
    <body><center>
    <div id="container">
        <label for="txtName">
        Name:
        </label>
        <input type="text" id="txtName" name="txtName" />
        <br />
        <label for="txtEmail">
        Email:
        </label>
        <input type="text" id="txtEmail" name="txtEmail" />
        <br />
        <input type="button" id="btnAdd" value="Add Record" />
        <br />
        <label for="AadharNumber">
        ID:
        </label>
        <input type="text" id="AadharNumber" name="txtAadharNumber" />
        <input type="button" id="btnDelete" value="Delete Record" />
        <br />
        <input type="button" id="btnPrint" value="Print Records" />
        <br />
        <output id="printOutput" > </output>
    </div>  
    </center>
    </body>
    </html>

1 个答案:

答案 0 :(得分:1)

使用旧版本的规范(setVersion)时,数据库的版本是字符串值。这就是每次加载时都会创建对象库的原因。我建议你提出以下建议:

if (db.setVersion) {
    if (parseInt(db.version) != dbVersion) {
        // Create the structure
    }
}

请注意,此实现仅适用于较旧的Firefox和Chrome浏览器。在较新版本的浏览器中,open方法具有onupgradeneeded回调。有关它的更多信息,请查看here

function initializeDB(){             
   var request = indexedDB.open("Customers",dbVersion);              
   request.onerror = function(event){ }; 
   request.onsuccess = function(event){ };
   request.onupgradeneeded = function (e){
      if(e.newVersion == dbVersion){
         var db = e.result;
         if(!db.objectStoreNames.contains("CustDetails")) {
             var objectStore = db.createObjectStore("CustDetails",{ Keypath: "AadharNumber", autoIncrement: true });                                     
             objectStore.createIndex("name", "name",{unique: false});                                 
             objectStore.createIndex("email", "email",{unique: true});

             // ....    
         }
      }
   };