U E D R , A S I H C RSS

html5/web Sql Database

1. 개요

  • SeeAlso) html5/web-storage
  • 로컬 저장소의 일부. html5/web-storage외에 추가 제공되는 것.
  • 브라우저 자체 경량 DB
  • web storage와 비교
    • WebStorage는 간단한 데이터를 저장하기 적합.
    • WebSqlDatabase는 보다 구조적이고 체계화된 관계형 데이터 베이스를 대량으로 저장
  • 안정적인 경량 관계형 자료구조 지원, 표준 SQL질의 지원
  • SQLite를 기반으로 하고 있다.

1.1. 브라우저 지원

  • 의외로 파이어폭스에서 지원하지 않는다.
    • 심지어 내부 디비가 sqlite 임에도 불구하고.
  • 아래의 코드를 이용하면 지원 여부를 확인 할 수 있다.
    if(!!window.openDatabase) {
         alert("현재 브라우저는 Web SQL Database를 지원합니다")
    }
    else{
          alert("현재 브라우저는 Web SQL Database를 지원하지 않습니다")
    }
    

1.2. Indexed Database

  • SeeAlso) html5/indexedDatabase
  • Indexed Database는 새로 등장한 또다른 로컬 저장소 스펙이다
  • 2009년 말까지 사양 책정이 진행중이던 Web SQL Database 의 대안으로 탄생했다
  • 현재 Web SQL Database 는 사양 책정이 중지된 상태이며, IndexedDB 라는 새로운 스펙이
대안으로 떠오르고 있다

2. 특징

  • 비동기 작업 이므로 UI에 최소한의 영향을 준다.
  • 도메인 단위로 DB가 분리된다.
    • 특정 도메인에서 생성된 디비는 다른 도메인에서 접근할 수 없다.
  • 일반적인 DB 사용법과 비슷하다. 열고, 수행하고, 닫고.

3. 사용법

  • 비동기 식이다.
  • transaction을 지원한다.
    • transaction(), readTransaction

3.1. 변수 선언

var html5rocks = {};
html5rocks.webdb = {};

3.2. 열기

  • 사용전에 반드시 데이터 베이스를 열어야 한다.

html5rocks.webdb.db = null;

html5rocks.webdb.open = function() {
  var dbSize = 5 * 1024 * 1024; // 5MB
  html5rocks.webdb.db = openDatabase('Todo', '1.0', 'todo manager', dbSize);
}

html5rocks.webdb.onError = function(tx, e) {
  alert('Something unexpected happened: ' + e.message );
}

html5rocks.webdb.onSuccess = function(tx, r) {
  // re-render all the data
  html5rocks.webdb.getAllTodoItems(tx, r);
}

3.3. 테이블 생성

  • todo table. ID, todo, added_on

html5rocks.webdb.createTable = function() {
  html5rocks.webdb.db.transaction(function(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS ' + 
                  'todo(ID INTEGER PRIMARY KEY ASC, todo TEXT, added_on DATETIME)', []);
  });
}

3.4. 테이블에 데이터 추가

  • dynamic sql

html5rocks.webdb.addTodo = function(todoText) {
  html5rocks.webdb.db.transaction(function(tx){
    var addedOn = new Date();
    tx.executeSql('INSERT INTO todo(todo, added_on) VALUES (?,?)', 
        [todoText, addedOn],
        html5rocks.webdb.onSuccess,
        html5rocks.webdb.onError);
    });
}

3.5. 검색 질의



html5rocks.webdb.getAllTodoItems = function(renderFunc) {
  html5rocks.webdb.db.transaction(function(tx) {
    tx.executeSql('SELECT * FROM todo', [], renderFunc, 
        html5rocks.webdb.onError);
  });
}

3.5.1. 결과 표시

function loadTodoItems(tx, rs) {
  var rowOutput = "";
  for (var i=0; i < rs.rows.length; i++) {
    rowOutput += renderTodo(rs.rows.item(i));
  }
  var todoItems = document.getElementById('todoItems');
  todoItems.innerHTML = rowOutput;
}

function renderTodo(row) {
  return '<li>' + row.ID  +
         '[<a onclick="html5rocks.webdb.deleteTodo(' + row.ID + ');"'>X</a>]</li>';
}

3.6. 데이터 지우기

html5rocks.webdb.deleteTodo = function(id) {
  html5rocks.webdb.db.transaction(function(tx) {
    tx.executeSql('DELETE FROM todo WHERE ID=?', [id],
        loadTodoItems, html5rocks.webdb.onError);
  });
}

3.7. hooking it all up

3.7.1. init

function init() {
  html5rocks.webdb.open();
  html5rocks.webdb.createTable();
  html5rocks.webdb.getAllTodoItems(loadTodoItems);
}
</script>

<body onload="init();">

3.7.2. adding

function addTodo() {
  var todo = document.getElementById('todo');

  html5rocks.webdb.addTodo(todo.value);
  todo.value = '';
}

3.8. transaction

var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "synergies")');
});

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:31:41
Processing time 0.0221 sec