Skip to content

indexeddb

2021.02.07 20:03

WHRIA 조회 수:106

로메오의 블로그 :: [Chrome] IndexedDB 사용하기 (tistory.com)

 

아래는 전체 코드입니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>IndexedDB</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

<body>

    companyName: <input type="text" id="companyName"><br>
    production: <input type="text" id="production"><br>
    <button id="submit">입력</button>
    <button id="clearAll">모두삭제</button>

    <ul id="lists"></ul>

<script>
const DATABASE = 'MyDatabase';
const DB_VERSION = 1;
const DB_STORE_NAME = 'company';

var db;

openDB = () => {
    // DB 생성
    var req = indexedDB.open(DATABASE, DB_VERSION);

    // DB 생성 성공
    req.onsuccess = function (evt) {
        db = this.result;
        getAllData();
    };
    // DB 생성 오류
    req.onerror = function (evt) {
        console.error("indexedDB : ", evt.target.errorCode);
    };
    // DB 마그레이션
    req.onupgradeneeded = function (evt) {
        console.log("indexedDB.onupgradeneeded");
        var store = evt.currentTarget.result.createObjectStore(DB_STORE_NAME,
            { keyPath: 'id', autoIncrement: true });

        store.createIndex('company', 'company', { unique: true });
        store.createIndex('production', 'production', { unique: false });
    };
}

openDB()

// Store를 반환한다.
getObjectStore = (store_name, mode) => {
    return db.transaction(store_name, mode).objectStore(store_name);
}

// 데이터 입력하기
$('#submit').on('click', () => {
    const companyName = $('#companyName').val()
    const production = $('#production').val()
    if (!companyName) {
        return alert('company name은 필수입니다.')
    }
    if (!production) {
        return alert('production은 필수입니다.')
    }

    // 입력한 데이터를 추가한다.
    let store = getObjectStore(DB_STORE_NAME, 'readwrite');
    let req
    const obj = { 
        company: companyName, 
        production: production
    };

    try {
        req = store.add(obj);
    } catch (e) { }

    req.onsuccess = function (evt) {
        console.log("입력 되었습니다.");
    };
    req.onerror = function () {
        console.error(this.error);
    };
})

// 모든 데이터를 가지고 온다.
getAllData = () => {
    // get
    store = getObjectStore(DB_STORE_NAME, 'readonly');
    let req = store.openCursor();
    let strBuffer = []
    req.onsuccess = evt => {
        const cursor = evt.target.result;
        if (cursor) {
            req = store.get(cursor.key);
            req.onsuccess = function (evt) {
                const value = evt.target.result;
                strBuffer.push('<li>')
                strBuffer.push(value.company + ' (' + value.production + ')')
                strBuffer.push(' [<a href="#" data-delete="' + value.id + '">삭제</a>]')
                strBuffer.push('</li>')
                console.log(value)
            }
            cursor.continue();
        }
        $('#lists').html(strBuffer.join(''))

        // 데이터를 삭제한다.
        $('[data-delete]').on('click', evt => {
            const id = $(evt.currentTarget).attr('data-delete')
            store = getObjectStore(DB_STORE_NAME, 'readwrite');
            store.delete(id)
                .onsuccess = event => {
                    console.log('deleted')
                }
        })
    }
}

// 데이터를 모두 삭제한다.
$('#clearAll').on('click', () => {
    // clear
    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
    var req = store.clear();
    req.onsuccess = function (evt) {
        console.log('clear')
    };
    req.onerror = function (evt) {
        console.log('error')
    };
})
</script>
</body>

</html>
번호 제목 글쓴이 날짜 조회 수
1671 개업 WHRIA 2009.11.03 9403
1670 내가 거래하는 은행에서 firefox 를 지원하다. WHRIA 2011.03.07 9396
1669 내년 피부과 개원 예정 WHRIA 2009.06.15 9317
1668 MBC 최강연승 퀴즈쇼 [2] WHRIA 2012.08.13 9300
1667 파일의 magic number WHRIA 2012.12.26 9272
1666 NEWTYPE 2003.11.18 9263
1665 홈페이지 이전 WHRIA 2010.12.12 9251
1664 승석아.. 안녕... 최평균 2000.05.31 9228
1663 GomPhoto 만들었음 [2] WHRIA 2012.12.31 9207
1662 clonezilla WHRIA 2011.05.10 9205
1661 우연히..... 이임숙 2000.05.30 9195
1660 계획 WHRIA 2009.10.05 9146
1659 bjam WHRIA 2008.02.29 9107
1658 Release MedicalPhoto 1.0.4 WHRIA 2008.05.14 9103
1657 기장, 간편장부 WHRIA 2008.08.30 9029

Powered by Xpress Engine / Designed by Sketchbook

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소