LoginSignup
10
14

More than 5 years have passed since last update.

indexedDB の基本をまとめてみた

Last updated at Posted at 2017-12-06

indexedDBとは

値とオブジェクトをローカルデータベースに保持するウェブブラウザの標準インターフェース


DBに接続

open

var request = window.indexedDB.open('MyTestDatabase')

第2引数にバージョンを指定することができる


エラーハンドラを設定する

var db;

// DB に接続
var request = indexedDB.open("MyDatabase");

// 接続失敗
request.onerror = function(event) {
 alert("接続に失敗しました");
};

// 接続成功
request.onsuccess = function() {
  db = event.target.result;
};

スキーマを作成

openするとonupgradeneededイベントが呼び出されます

var db
var request = indexedDB.open('MyDatabase', 1)
var index
var store
request.onupgradeneeded = function () {
    db = request.result

    // MyObjectStore を作成 key は id
    store = db.createObjectStore('MyObjectStore', {keyPath: 'id'})

    // インデックスを作成 key は name.last, name.first 
    index = store.createIndex('NameIndex', ['name.last', 'name.first'])
}

データの書き込み

db = request.result

//  readwrite : 読み書きを開始
var tx = db.transaction('MyObjectStore', 'readwrite')
store = tx.objectStore('MyObjectStore')
index = store.index('NameIndex')

// データの追加
store.put({id: 12345, name: {first: 'John', last: 'Doe'}, age: 42})
store.put({id: 67890, name: {first: 'Bob', last: 'Smith'}, age: 35})

データの呼び出し

// store からデータ取得 key は id
var getJohn = store.get(12345)
// => {id: 12345, name: {first: 'John', last: 'Doe'}, age: 42}

// index からデータ取得 key は [name.last, name.first]
var getBob = index.get(['Smith', 'Bob'])
// => {id: 67890, name: {first: 'Bob', last: 'Smith'}, age: 35}

getJohn.onsuccess = function () {
  console.log(getJohn.result.name.first)  // => "John"
}

getBob.onsuccess = function () {
  console.log(getBob.result.name.first)   // => "Bob"
}

// 読み書き終了
tx.oncomplete = function () {
  db.close()
}

参考

IndexedDB を使用する - Web API インターフェイス | MDN

10
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
14