indexedDB添加,刪除,獲取,修改

在chrome(版本 70.0.3538.110)測試正常
編寫涉及:css, html, jscss

在線演示codepenhtml

html代碼

<h1>indexedDB</h1>
<h2>在 DevTools 的 Application 中查看數據庫信息</h2>

<button onclick="addDBData()">添加數據</button>
<div>
    <button onclick="getDBData()">獲取數據</button>
    <input type="text" id="getID" placeholder="請輸入ID">
</div>
<div>
    <button onclick="delDBData()">刪除數據</button>
    <input type="text" id="delID" placeholder="請輸入ID">
</div>
<div>
    <button onclick="updateDBData()">更新數據</button>
    <input type="text" id="updateID" placeholder="請輸入ID">
</div>
<div id="display"></div>

css代碼

button {
    margin: 10px 0;
    padding: 8px 10px;
    border: 0;
    color: #fff;
    background-color: rgb(7, 196, 230);
}
input{
    padding: 8px 5px;
    border: rgb(7, 196, 230) solid 1px
}

JavaScript代碼

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
if (!window.indexedDB) {
    alert('不支持indexDB')
}

const DATA_BASE = 'TEST_DB'
let db = {}

/**
    1. 不存在當前數據庫時,即爲建立
    2. open參數:數據庫名稱,版本號(整數)
*/
const request = window.indexedDB.open(DATA_BASE, 1) 

request.onerror = function (e) {
    console.error('error', e)
}

/**
    1. 數據庫已存在,打開成功
*/
request.onsuccess = function (event) {
    db = event.target.result
    console.log('execute onsuccess');
};

/**
    1. 當數據庫不存在時,建立數據庫會觸發 onupgradeneeded 事件
    2. 當指定的版本號高於當前時會直接觸發 onupgradeneeded 事件
    3. 惟一能夠修改數據庫結構的事件
*/
request.onupgradeneeded = function (event) {
    /**
        1. 保存 IDBDataBase 接口(數據庫)
    */
    db = event.target.result
    console.log('execute onupgradeneeded');

    /**
        1.使用鍵生成器,測試時,去除註釋便可
    */
    // const objectStore = db.createObjectStore('users', { autoIncrement : true })
    // objectStore.add({name: '123'});
    // objectStore.add('123');

    /**
        1. 爲當前數據庫建立對象倉庫(表) 
        2. 這裏的keyPath 至關於主鍵
        3. createIndex(indexName, keyPath, {unique | multiEntry | locale})
    */
    const objectStore = db.createObjectStore('users', { keyPath: 'id' })
    objectStore.createIndex('name', 'name', { unique: false })
    objectStore.createIndex('age', 'age', { unique: false })

    /**
        1. 確保初始化數據的時候,對象倉庫已經建立完畢
    */
    objectStore.transaction.oncomplete = function(event) {
        const transaction = db.transaction(['users'], 'readwrite')
        const objStore = transaction.objectStore('users')
        objStore.add({
            id: 12, 
            name: `hew-${Math.random()}` ,
            age: parseInt( Math.random() * 100, 10)
        })
    }
}

/**
    1. 全部數據庫操做都基於事務
    2. 事務三種模式:readonly,readwrite,versionchange
    3. 修改數據庫模式或結構——包括新建或刪除對象倉庫或索引,只能用 versionchange 模式
*/
function addDBData() {
    const transaction = db.transaction(['users'], 'readwrite')
    const objectStore = transaction.objectStore('users')
    const request = objectStore.add({ 
        id: Math.random() * 10, 
        name: `hew-${Math.random()}` ,
        age: parseInt( Math.random() * 100, 10)
    })

    transaction.oncomplete = function (event) {
        console.log('transaction add complete')
    }

    transaction.onerror = function (error) {
        console.error('add error', error)
    }

    request.onsuccess = function (event) {
        console.log('add complete')
    }
}

function getDBData() {
    const id = parseFloat(document.getElementById('getID').value)
    const transaction = db.transaction(['users'], 'readwrite')
    const objectStore = transaction.objectStore('users')

    /**
        1. 注意數據類型
    */
    const request = objectStore.get(id)

    request.onsuccess = function (event) {
        console.log('get complete', event.target.result)
        document.getElementById('display').innerHTML = JSON.stringify(request.result)
    }

    request.onerror = function (err) {
        console.error('get error', err)
    }
}

function updateDBData() {
    const id = parseFloat(document.getElementById('updateID').value)
    const transaction = db.transaction(['users'], 'readwrite')
    const objectStore = transaction.objectStore('users')
    const request = objectStore.get(id)

    request.onsuccess = function (event) {
        const d = event.target.result
        d.name = 'name name'
        const objectStoreUpdate = objectStore.put(d)
        objectStoreUpdate.onsuccess = function (e) {
            console.log('update success')
        }
        
        document.getElementById('display').innerHTML = 'update success'
    }

    request.onerror = function (err) {
        console.error('get error', err)
    }
        
}

function delDBData() {
    const id = parseFloat(document.getElementById('delID').value)
    const request = db.transaction(['users'], 'readwrite').objectStore('users').delete(id)

    request.onsuccess = function() {
        console.log('delete complete', id);
    }
}

參考java

如有疑問或錯誤,請留言,謝謝!Github blog issuesgit

相關文章
相關標籤/搜索