Suche…


Bemerkungen

Transaktionen

Transaktionen müssen sofort nach ihrer Erstellung verwendet werden. Wenn sie nicht in der aktuellen Ereignisschleife verwendet werden (im Wesentlichen bevor wir auf eine Webanforderung warten), werden sie in einen inaktiven Status versetzt, in dem sie nicht verwendet werden können.

Datenbanken können nur eine Transaktion haben, die jeweils in einen bestimmten Objektspeicher schreibt. Sie können also beliebig viele davon in unserem things Store lesen, aber nur einer kann zu einem bestimmten Zeitpunkt Änderungen vornehmen.

Testen der Verfügbarkeit von IndexedDB

Sie können die IndexedDB-Unterstützung in der aktuellen Umgebung testen, indem Sie das Vorhandensein der Eigenschaft window.indexedDB :

if (window.indexedDB) {
    // IndexedDB is available
}

Datenbank öffnen

Das Öffnen einer Datenbank ist ein asynchroner Vorgang. Wir müssen eine Anfrage zum Öffnen unserer Datenbank senden und dann auf Ereignisse achten, damit wir wissen, wann sie fertig ist.

Wir werden eine DemoDB-Datenbank öffnen. Wenn es noch nicht existiert, wird es erstellt, wenn wir die Anfrage senden.

Die 2 unten sagt aus, dass wir nach Version 2 unserer Datenbank fragen. Es gibt immer nur eine Version, aber wir können die Versionsnummer verwenden, um alte Daten zu aktualisieren, wie Sie sehen werden.

var db = null, // We'll use this once we have our database
    request = window.indexedDB.open("DemoDB", 2);

// Listen for success. This will be called after onupgradeneeded runs, if it does at all
request.onsuccess = function() {
    db = request.result; // We have a database!

    doThingsWithDB(db);
};

// If our database didn't exist before, or it was an older version than what we requested,
// the `onupgradeneeded` event will be fired.
// 
// We can use this to setup a new database and upgrade an old one with new data stores
request.onupgradeneeded = function(event) {
    db = request.result;

    // If the oldVersion is less than 1, then the database didn't exist. Let's set it up
    if (event.oldVersion < 1) {
        // We'll create a new "things" store with `autoIncrement`ing keys
        var store = db.createObjectStore("things", { autoIncrement: true });
    }

    // In version 2 of our database, we added a new index by the name of each thing
    if (event.oldVersion < 2) {
        // Let's load the things store and create an index
        var store = request.transaction.objectStore("things");

        store.createIndex("by_name", "name");
    }
};

// Handle any errors
request.onerror = function() {
    console.error("Something went wrong when we tried to request the database!");
};

Objekte hinzufügen

Alles, was mit Daten in einer IndexedDB-Datenbank geschehen muss, geschieht in einer Transaktion. Zu Transaktionen, die im Abschnitt "Anmerkungen" am Ende dieser Seite erwähnt werden, sind einige Punkte zu beachten.

Wir verwenden die Datenbank, die wir in Datenbank öffnen eingerichtet haben .

// Create a new readwrite (since we want to change things) transaction for the things store
var transaction = db.transaction(["things"], "readwrite");

// Transactions use events, just like database open requests. Let's listen for success
transaction.oncomplete = function() {
    console.log("All done!");
};

// And make sure we handle errors
transaction.onerror = function() {
    console.log("Something went wrong with our transaction: ", transaction.error);
};

// Now that our event handlers are set up, let's get our things store and add some objects!
var store = transaction.objectStore("things");


// Transactions can do a few things at a time. Let's start with a simple insertion
var request = store.add({
    // "things" uses auto-incrementing keys, so we don't need one, but we can set it anyway
    key: "coffee_cup",
    name: "Coffee Cup",
    contents: ["coffee", "cream"]
});

// Let's listen so we can see if everything went well
request.onsuccess = function(event) {
    // Done! Here, `request.result` will be the object's key, "coffee_cup"
};


// We can also add a bunch of things from an array. We'll use auto-generated keys
var thingsToAdd = [{ name: "Example object" }, { value: "I don't have a name" }];

// Let's use more compact code this time and ignore the results of our insertions
thingsToAdd.forEach(e => store.add(e));

Daten abrufen

Alles, was mit Daten in einer IndexedDB-Datenbank geschehen muss, geschieht in einer Transaktion. Zu Transaktionen, die im Abschnitt "Anmerkungen" am Ende dieser Seite erwähnt werden, sind einige Punkte zu beachten.

Wir verwenden die Datenbank, die wir in Datenbank öffnen eingerichtet haben.

// Create a new transaction, we'll use the default "readonly" mode and the things store
var transaction = db.transaction(["things"]);

// Transactions use events, just like database open requests. Let's listen for success
transaction.oncomplete = function() {
    console.log("All done!");
};

// And make sure we handle errors
transaction.onerror = function() {
    console.log("Something went wrong with our transaction: ", transaction.error);
};

// Now that everything is set up, let's get our things store and load some objects!
var store = transaction.objectStore("things");


// We'll load the coffee_cup object we added in Adding objects
var request = store.get("coffee_cup");

// Let's listen so we can see if everything went well
request.onsuccess = function(event) {
    // All done, let's log our object to the console
    console.log(request.result);
};


// That was pretty long for a basic retrieval. If we just want to get just
// the one object and don't care about errors, we can shorten things a lot
db.transaction("things").objectStore("things")
    .get("coffee_cup").onsuccess = e => console.log(e.target.result);


Modified text is an extract of the original Stack Overflow Documentation
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow