-
[JavaScript] IndexedDB 기초사용법JavaScript 2023. 4. 16. 01:32반응형
IndexedDB는 클라이언트단에서 간단하게 사용할 수 있는 내장DB로,
사용법을 기록으로 남기고자 한다.
1. 사용할 db생성 + 테이블 생성
const DBOpenRequest = window.indexedDB.open('testDB', 1); //db이름, 버전 DBOpenRequest.onerror = (event) => { console.log('Error loading database.'); }; DBOpenRequest.onsuccess = (event) => { console.log('Database initialised.'); db = DBOpenRequest.result; }; DBOpenRequest.onupgradeneeded = (event) => { db = event.target.result; db.onerror = (event) => { console.log('Error loading database.'); }; // 테이블생성, pk이름 지정 const objectStore = db.createObjectStore('testTable', { keyPath: 'pk' }); // 칼럼 생성. 현재는 "test"칼럼 하나만 생성함. 필요시 추가 objectStore.createIndex('test', 'test', { unique: false }); };
트랜잭션 준비
const transaction = db.transaction(['testTable'], 'readwrite'); transaction.oncomplete = () => {console.log('Transaction completed: database modification finished.');}; transaction.onerror = () => { console.log(`Transaction not opened due to error: ${transaction.error}`);}; const objectStore = transaction.objectStore('testTable');
insert
const newItem = [ { pk: Date.now(), test: "test"}, ]; const objectStoreRequest = objectStore.add(newItem[0]); objectStoreRequest.onsuccess = (event) => { console.log('insert Request successful.'); };
select
const objectStore = db.transaction('testTable').objectStore('testTable'); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (!cursor) { console.log('Entries all displayed.'); return; } // Check which suffix the deadline day of the month needs const { test, pk } = cursor.value; dbObj[pk] = cursor.value; cursor.continue(); };
update
let key = Number(Object.keys(dbObj)[0]); //첫번째 row; let tg = objectStore.get(key); tg.onsuccess = e => { let toUpdate = e.target.result; toUpdate.test = new Date().toLocaleString('ko-KR'); const updateRequest = objectStore.put(toUpdate); updateRequest.onsuccess = e => { console.log("update complete"); }
delete
코드전문
let db, dbObj = new Object(); document.addEventListener('DOMContentLoaded', function(){ idxdb.initIdxDB(); }) idxdb = { initIdxDB : function(){ const DBOpenRequest = window.indexedDB.open('testDB', 1); DBOpenRequest.onerror = (event) => { console.log('Error loading database.'); }; DBOpenRequest.onsuccess = (event) => { console.log('Database initialised.'); db = DBOpenRequest.result; idxdb.connectDB('select'); }; DBOpenRequest.onupgradeneeded = (event) => { db = event.target.result; db.onerror = (event) => { console.log('Error loading database.'); }; const objectStore = db.createObjectStore('testTable', { keyPath: 'pk' }); objectStore.createIndex('test', 'test', { unique: false }); }; }, connectDB : function(keyword){ const transaction = db.transaction(['testTable'], 'readwrite'); transaction.oncomplete = () => {console.log('Transaction completed: database modification finished.');}; transaction.onerror = () => { console.log(`Transaction not opened due to error: ${transaction.error}`);}; const objectStore = transaction.objectStore('testTable'); if(keyword.includes('add')){ const newItem = [ { pk: Date.now(), test: "test"}, ]; const objectStoreRequest = objectStore.add(newItem[0]); objectStoreRequest.onsuccess = (event) => { console.log('insert Request successful.'); }; } else if(keyword.includes('update')){ let key = Number(Object.keys(dbObj)[0]); //첫번째 row; let tg = objectStore.get(key); tg.onsuccess = e => { let toUpdate = e.target.result; toUpdate.test = new Date().toLocaleString('ko-KR'); const updateRequest = objectStore.put(toUpdate); updateRequest.onsuccess = e => { console.log("update complete"); } }; } else if(keyword.includes('select')){ const objectStore = db.transaction('testTable').objectStore('testTable'); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (!cursor) { console.log('Entries all displayed.'); return; } const { test, pk } = cursor.value; dbObj[pk] = cursor.value; cursor.continue(); }; } else { const key = Number(Object.keys(dbObj)[0]); //첫번째 row; objectStore.delete(key); transaction.oncomplete = () => { console.log("1번째 row 삭제완료"); }; } }, }
반응형'JavaScript' 카테고리의 다른 글
[JavaScript] 입력받은 데이터가 Date 타입인지 체크 (0) 2023.07.09 [JavaScript] node.js를 이용한 간단한 WEB SCRAPER만들기 (0) 2023.05.13 [JavaScript] Sleep 기능 구현하기. (0) 2023.02.23 [JavaScript] Object와 Map의 차이 (0) 2023.02.13 [JavaScript] 간단한 로또시뮬레이션 중복제거 2등판별 등 (0) 2023.01.21