初窺IndexedDB

寫在前面

9月初的時候作了一個Todos,當時在想若是不作用戶管理但又想讓每一個客戶端都只顯示本身的代辦事項該怎麼作。就想到要用indexedDB來處理一下,可是一直在實習準備秋招,今天有時間就來看看這個瀏覽器的數據庫IndexedDB。javascript

正篇開始

  1. 鏈接數據庫 開頭第一步,和操做其餘數據庫同樣,先鏈接java

    const request = indexedDB.open('數據庫名稱', 數據庫版本)
    複製代碼

    鏈接時,會觸發三種事件error(失敗)、success(成功)、upgradeneeded(升級)數據庫

    request.onerror = function(event) {
        // 鏈接失敗事觸發事件
    }
    request.onsuccess = function(event) {
        // 鏈接成功觸發事件
    }
    request.onupgradeneeded = function(event) {
        // 數據庫更新時觸發事件,若是沒有數據庫或者更新數據庫版本時,會先觸發upgradeneeded事件,再觸發success事件
        
        // 數據庫實例
        db = event.target.result;
        
        if (!db.objectStoreNames.contains('person')) {
            // 新建表, 新建一個表名爲person,主鍵爲id的表(只能在更新時使用createObjectStore方法建立對象)
            let objectStore = db.createObjectStore('person', { keyPath: 'id' });
            // 新建索引,createIndex方法分別有三個參數,分別爲索引名稱、索引所在的屬性、配置對象(代表該屬性的值是否能夠重複)
            objectStore.createIndex('name', 'name', { unique: false });
            objectStore.createIndex('email', 'email', { unique: true });
        }
    }
    複製代碼

    鏈接成功,就能夠對數據庫進行操做了瀏覽器

    const request = db
        // 新建事務,參數:訪問的表,以及訪問權限
        .transaction(['person'], 'readwrite')
        // 獲得表實例
        .objectStore('preson')
        // 添加數據
        .add({id:1, name: '張三', age: 30, email: 'zhangsan@text.com'})
        
    // 同時也擁有成功和失敗的回調函數
    request.onsuccess = function(event){
        console.log('成功')
    }
    request.onerror = function(event){
        console.log('失敗')
    }
    複製代碼
    const request = db
        .transaction('[person]', readwrite)
        .objectStore('person')
        // 刪除主鍵爲2的數據
        .delete(1);
        
    // 同時也擁有成功和失敗的回調函數
    複製代碼

    3.改緩存

    const request = db
        .transaction('[person]', 'readwrite')
        .objectStore('person')
        // 更新數據,根據主鍵更新數據,若是沒有改主鍵會插入一條新的數據
        .put({ id: 1, name: '王五', age: 50, email: 'wangwu@example.com' })
    複製代碼

    4.查函數

    const request1 = db
        .transaction('[person]', 'readwrite')
        .objectStore('person')
        // 根據主鍵查詢數據
        .get(1);
        
    const request2 = db
        .transaction('[person]', 'readwrite')
        .objectStore('person')
        // 查詢全部數據
        .openCursor();
        
    const request3 = db
        .transaction('[person]', 'readwrite')
        .objectStore('person')
        // 設置查詢的索引值
        .index('name')
        .get('王五');
        
        
    // 全部查詢到的數據都在成功回調函數中
    request.onsuccess = function(event) {
        // 查詢到的數據
        let result = event.target.result
    }
    複製代碼

結束

IndexedDB可能在平常開發中用處較少,可是用在本地作一些緩存數據,或者其餘與數據相關聯的內容,仍是很不錯的。ui

相關文章
相關標籤/搜索