開啟資料庫
開啟資料庫是一種非同步操作。我們需要傳送一個請求來開啟我們的資料庫然後監聽事件,以便我們知道什麼時候準備就緒。
我們將開啟一個 DemoDB 資料庫。如果它還不存在,它將在我們傳送請求時建立。
下面的 2
說我們要求我們的資料庫的第 2 版。你可以隨時只使用一個版本,但我們可以使用版本號升級舊資料,如你所見。
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!");
};