javascript – Get all data from a table in a JSON – Indexeddb

Question:

Hi! I need to get all the data from a table in a JSON. (Using Indexeddb database). How to proceed?

Answer:

follow the steps

1 – Step: read the Mozilla website

2 – Step: Create the indexedDB database

var cidades = [
{
  "cidade":"cidadeum",
  "latitude":-25.2985296,
  "longitude":-57.6710677
},
{
  "cidade":"cidadedois",
  "latitude":-25.465034,
  "longitude":-56.0183859
},
{
  "cidade":"cidadetres",
  "latitude":-25.4933441,
  "longitude":-54.6710438
},
 {
  "cidade":"cidadequatro",
  "latitude":-24.1586759,
  "longitude":-56.636503
},
 {
  "cidade":"cidadecinco",
  "latitude":-22.5450875,
  "longitude":-55.7618963
}
];

var IDBSetting = {
    name: "indexedDBName",
    version: 1,
    tables: [{
        tableName: "cidades",
        keyPath: "seq",
        autoIncrement: true,
        index: ["cidade", "latitude", "longitude"],
        unique: [false, false, false]
    }]
};

! function() {
    console.log("indexeDB init");

    var req = indexedDB.open(IDBSetting.name, IDBSetting.version);

    req.onsuccess = function(event) {
        console.log("indexedDB open success");
    };

    req.onerror = function(event) {
        console.log("indexed DB open fail");
    };

    //callback run init or versionUp
    req.onupgradeneeded = function(event) {
        console.log("init onupgradeneeded indexedDB ");
        var db = event.target.result;

        for (var i in IDBSetting.tables) {
            var OS = db.createObjectStore(IDBSetting.tables[i].tableName, {
                keyPath: IDBSetting.tables[i].keyPath,
                autoIncrement: IDBSetting.tables[i].autoIncrement
            });

            for (var j in IDBSetting.tables[i].index) {
                OS.createIndex(IDBSetting.tables[i].index[j], IDBSetting.tables[i].index[j], {
                    unique: IDBSetting.tables[i].unique[j]
                });
            }
        }
    }
}();

3 – Step: addData – Adding data

var IDBFuncSet = {
    //write
    addData: function(table, data) {
        var req = indexedDB.open(IDBSetting.name, IDBSetting.version);

        req.onsuccess = function(event) {
            try {
                console.log("addData indexedDB open success");
                var db = req.result;
                var transaction = db.transaction([table], "readwrite");
                var objectStore = transaction.objectStore(table);
                var objectStoreRequest = objectStore.add(data);
            } catch (e) {
                console.log("addDataFunction table or data null error");
                console.log(e);
            }

            objectStoreRequest.onsuccess = function(event) {
                //console.log("Call data Insert success");
            }
            objectStoreRequest.onerror = function(event) {
                console.log("addData error");
            }
        };

        req.onerror = function(event) {
            console.log("addData indexed DB open fail");
        };
    }
}

for(var i in cidades){
   IDBFuncSet.addData("cidades",cidades[i]);
}

4 – Step: getAllData – Returning all data

IDBFuncSet.getAllData = function(arr, table) {
    try {
        var req = indexedDB.open(IDBSetting.name, IDBSetting.version);

        req.onsuccess = function(event) {
            var db = req.result;
            var transaction = db.transaction([table], "readonly");
            var objectStore = transaction.objectStore(table);

            var objectStoreRequest = objectStore.openCursor();

            objectStoreRequest.onsuccess = function(event) {
                var cursor = event.target.result;
                if (cursor) {
                    arr.push(cursor.value);
                    cursor.continue();
                } else {

                }
            }
        };
        req.onerror = function(event) {
            console.log("getAllData indexed DB open fail");
        };
    } catch (e) {
        console.log(e);
    }
}
var cidadesArr = [];
IDBFuncSet.getAllData(cidadesArr, "cidades");

console.log(cidadesArr);

Other Tutorial

Recover all data

If you want to get all the data instead of an object store then you might need to use a cursor. Here is another function that makes use of cursor to retrieve all data from the object store:

function readAll() {
        var objectStore = db.transaction("customers").objectStore("customers");

        objectStore.openCursor().onsuccess = function(event) {
          var cursor = event.target.result;
          if (cursor) {
                alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
                cursor.continue();
          }
          else {
                alert("Não há mais entradas!");
          }
        };     
}

As you can see, we implemented the openCursor() method to accomplish the goal. openCursor() is used to iterate over multiple records in a database. It can accept various parameters, such as limiting the scale items, the direction we want to iterate and so on. In this case, we leave no parameters.

The cursor object itself is the result of the order. We have to implement the continue() function to continue with the next iteration in the circuit. When the loop comes to an end then we will get the alert with the content "No more entries!".

See the demo: http://www.onlywebpro.com/demo/jquery/indexeddb.html

Source: http://www.onlywebpro.com/2012/12/23/html5-storage-indexeddb/


There is also a lib you can implement with indexedDB :

http://objectdb.kganser.com


Hope this helps.

Scroll to Top