IndexedDB Basic Operations (no project practice for beginners only)

Keywords: Javascript Database MySQL

Operation is all asynchronous

Open database

indexedDB.open() is an open API and can also set a version number for an open database

// Open database
let request, database;

request = indexedDB.open('test');

request.onerror = function (event) {
    console.log(event);
}

request.onsuccess = function (event) {
    console.log(event);

    database = event.target.result;

    // Set Version Number
    if (database.version != '1.0') {
        request = database.setVersion('1.0');

        request.onerror = function (event) {
        console.log(`Error Code ${event.target.errorCode}`);
        }

        request.onsuccess = function (event) {
            console.log(`The database has been set up ${database.name}Version of ${database.version}`);
        }
    } else {
        console.log(`data base ${database.name}Version number of ${database.version}`);
    }
}

Closing the browser and calling open again after the database is first opened is equivalent to connecting to the database.

Database Build Table, Insert store

Inserting an object in indexedDB, similar to table building in MySQL, requires a database to be built before it can be invoked. The API is database.createObjectStore("books", {keyPath: "isbn"}), note that this method can only be used in the onupgradeneeded method in the open callback

Create multiple storage spaces in one version

A version creates multiple storage spaces, which can only be created one time in onupgradeneeded when the database is updated or created.

// Example from w3c
// createIndex is used here to create storage for different keypath s
const request = indexedDB.open("library");
let db;

request.onupgradeneeded = function() {
  // The database did not previously exist, so create object stores and indexes.
  const db = request.result;
  const store = db.createObjectStore("books", {keyPath: "isbn"});
  const titleIndex = store.createIndex("by_title", "title", {unique: true});
  const authorIndex = store.createIndex("by_author", "author");

  // Populate with initial data.
  store.put({title: "Quarry Memories", author: "Fred", isbn: 123456});
  store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
  store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678});
};

request.onsuccess = function() {
  db = request.result;
};

Update database

Upgrade the database version with the second parameter of indexedDB.open(database, version). Note that version can only be greater than or equal to the latest version, onsuccess can be triggered when it is equal to, onupgradeneeded, onsuccess methods can be triggered when it is greater than, and it should be noted that version cannot be a floating point number, otherwise 2.4 => 2 will not trigger the onupgradeneeded method

affair

indexedDB.transaction can be used in callbacks onsuccess and onupgradeneeded in open to add, delete, and alter data that looks at storage space in the database

Operations on data
let db = request.result;
let transaction = db.transaction('books2', 'readwrite');
let store = transaction.objectStore('books2');

//let addRequest1 = store.add({
//    author: 'lalala2',
//    title:'2 for testing',
//    isbn: 324552
//});

//addRequest1.onerror = function(e){
//    console.log('failed', e);
//}
//addRequest1.onsuccess = function(e){
//    console.log('Success', e);
//}
let addRequest = store.add({
    author: 'lalala',
    title: '1 for testing',
    isbn: 334552
});
let addRequest = store.add({
    author: 'lalala',
    title: '1 for testing',
    isbn: 334552
});

addRequest.onerror = function(e){
    console.log(e);
}
addRequest.onsuccess = function(e){
    let getAdd = store.get(e.target.result);
    getAdd.onsuccess = function(e){
        console.log(e);
    }
    getAdd.onerror = function(e){
        console.log(e);
    }
}
//let addRequest2 = store.add({
//    author: 'lalala1',
//    title:'1 for testing',
//    isbn: 314552
//});

//addRequest2.onerror = function(e){
//    console.log('failed', e);
//}
//addRequest2.onsuccess = function(e){
//    console.log('Success', e);
//}
let deleteData = store.delete(234567);
deleteData.onsuccess = function(e){
    console.log('delete', e);
}
  1. Transactions are asynchronous
  2. Modifying, deleting, adding data does not refresh immediately in the console, but it is available
  3. If one of the add-delete checks fails in the same transaction, subsequent operations will fail, such as the code above. If you add data first and then annotated data, subsequent annotated data will fail.
  4. After get gets the data, you can modify it and put it again, for example, you can see on the mdn

cursor

It can be understood as Object.keys(), but openCursor accepts two parameters that make it easier to traverse the entire storage space.

  1. First parameter IDKeyRange
  2. The second parameter, next, prev, nextunique, prevunique (the last two possible cases of data used for cursor queries will only return the smallest key value, but when IDKeyRange uses keypath s to create storage spaces, it will rarely have one key value indexed to more than one data) to traverse the order
// Here is the storage space for different keypath s, which can be used with IDKeyRange to specify unique key values
const tx = db.transaction("books", "readonly");
const store = tx.objectStore("books");
const index = store.index("by_author");

let keyRange = IDBKeyRange.bound("Barney", "Fred", false, true);

index.openCursor(keyRange, 'next').onsuccess = function(e){
    console.log(e);
    let cursor = e.target.result;
    if(cursor){
        console.log('Existing cursor', `name: ${cursor.value.author},title: ${cursor.value.title}`);
        cursor.continue();
    } else {
        console.log('Cursor Failure');
    }
};

In addition, API s for various IDKeyRange s can be queried in mdn

Posted by CodeBuddy on Sun, 08 Dec 2019 00:33:10 -0800