Toggle menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Html5/webSqlDatabase: Difference between revisions

From ZeroWiki
imported>beonit
No edit summary
(Repair batch-0008 pages from live compare)
 
(5 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[pagelist(html5)]]
<!-- MONIWIKI PageList(html5) -->
* [[html5]]
* [[html5/VA]]
* [[html5/canvas]]
* [[html5/communicationAPI]]
* [[html5/drag-and-drop]]
* [[html5/form]]
* [[html5/geolocation]]
* [[html5/offline-web-application]]
* [[html5/others-api]]
* [[html5/outline]]
* [[html5/overview]]
* [[html5/richtext-edit]]
* [[html5/section]]
* [[html5/video&audio]]
* [[html5/web-storage]]
* [[html5/web-workers]]
* [[html5/webSqlDatabase]]
* [[html5/websocket]]
* [[html5/문제점]]
* [[html5practice]]
* [[html5practice/roundRect]]
* [[html5practice/계층형자료구조그리기]]
* [[html5practice/즐겨찾기목록만들기]]
__TOC__
__TOC__
= 개요 =
= 개요 =
* 로컬 저장소의 일부. [[html5/webStorage]]외에 추가 제공되는 것.
* SeeAlso) [[html5/web-storage]]
* 로컬 저장소의 일부. [[html5/web-storage]]외에 추가 제공되는 것.
* 브라우저 자체 경량 DB
* 브라우저 자체 경량 DB
* web storage와 비교
* web storage와 비교
** WebStorage는 간단한 데이터를 저장하기 적합.
** WebStorage는 간단한 데이터를 저장하기 적합.
** WebSqlDatabase는 보다 구조적이고 체계화된 관계혀 데이터 베이스를 대량으로 저장
** WebSqlDatabase는 보다 구조적이고 체계화된 관계형 데이터 베이스를 대량으로 저장
* 안정적인 경량 관계형 자료구조 지원, 표준 SQL질의 지원
* 안정적인 경량 관계형 자료구조 지원, 표준 SQL질의 지원
  *SQLite를 기반으로 하고 있다.
  *SQLite를 기반으로 하고 있다.
== 브라우저 지원 ==
== 브라우저 지원 ==
* 의외로 파이폭스에서 지원하지 않는다.
* 의외로 파이어폭스에서 지원하지 않는다.
** '''심지어 내부 디비가 sqlite 임에도 불구하고.'''
** '''심지어 내부 디비가 sqlite 임에도 불구하고.'''
* 아래의 코드를 이용하면 지원 여부를 확인 할 수 있다.
* 아래의 코드를 이용하면 지원 여부를 확인 할 수 있다.
Line 20: Line 44:
  }
  }
== Indexed Database ==
== Indexed Database ==
* SeeAlso) [[html5/indexedDatabase]]
* SeeAlso) html5/indexedDatabase
* Indexed Database는 새로 등장한 또다른 로컬 저장소 스펙이다
* Indexed Database는 새로 등장한 또다른 로컬 저장소 스펙이다
* 2009년 말까지 사양 책정이 진행중이던 Web SQL Database 의 대안으로 탄생했다
* 2009년 말까지 사양 책정이 진행중이던 Web SQL Database 의 대안으로 탄생했다
Line 36: Line 60:
**  
**  
  transaction()
  transaction()
, {{{readTransaction}}}
, readTransaction
== 변수 선언 ==
== 변수 선언 ==
  var html5rocks = {};
  var html5rocks = {};
  html5rocks.webdb = {};
  html5rocks.webdb = {};
}}
== 열기 ==
== 열기 ==
* 사용전에 반드시 데이터 베이스를 열어야 한다.
  * 사용전에 반드시 데이터 베이스를 열어야 한다.
{{{
  html5rocks.webdb.db = null;
  html5rocks.webdb.db = null;
   
   
Line 65: Line 87:
   html5rocks.webdb.db.transaction(function(tx) {
   html5rocks.webdb.db.transaction(function(tx) {
     tx.executeSql('CREATE TABLE IF NOT EXISTS ' +  
     tx.executeSql('CREATE TABLE IF NOT EXISTS ' +  
                   'todo(ID INTEGER PRIMARY KEY ASC, todo TEXT, added_on DATETIME)', []);
                   'todo(ID INTEGER PRIMARY KEY ASC, todo TEXT, added_on DATETIME)', &#91;&#93;);
   });
   });
  }
  }
Line 74: Line 96:
     var addedOn = new Date();
     var addedOn = new Date();
     tx.executeSql('INSERT INTO todo(todo, added_on) VALUES (?,?)',  
     tx.executeSql('INSERT INTO todo(todo, added_on) VALUES (?,?)',  
         [todoText, addedOn],
         &#91;todoText, addedOn&#93;,
         html5rocks.webdb.onSuccess,
         html5rocks.webdb.onSuccess,
         html5rocks.webdb.onError);
         html5rocks.webdb.onError);
Line 83: Line 105:
  html5rocks.webdb.getAllTodoItems = function(renderFunc) {
  html5rocks.webdb.getAllTodoItems = function(renderFunc) {
   html5rocks.webdb.db.transaction(function(tx) {
   html5rocks.webdb.db.transaction(function(tx) {
     tx.executeSql('SELECT * FROM todo', [], renderFunc,  
     tx.executeSql('SELECT * FROM todo', &#91;&#93;, renderFunc,  
         html5rocks.webdb.onError);
         html5rocks.webdb.onError);
   });
   });
Line 99: Line 121:
  function renderTodo(row) {
  function renderTodo(row) {
   return '&lt;li&gt;' + row.ID  +
   return '&lt;li&gt;' + row.ID  +
           '[&lt;a onclick="html5rocks.webdb.deleteTodo(' + row.ID + ');"'&gt;X&lt;/a&gt;]&lt;/li&gt;';
           '&#91;&lt;a onclick="html5rocks.webdb.deleteTodo(' + row.ID + ');"'&gt;X&lt;/a&gt;&#93;&lt;/li&gt;';
  }
  }
== 데이터 지우기 ==
== 데이터 지우기 ==
  html5rocks.webdb.deleteTodo = function(id) {
  html5rocks.webdb.deleteTodo = function(id) {
   html5rocks.webdb.db.transaction(function(tx) {
   html5rocks.webdb.db.transaction(function(tx) {
     tx.executeSql('DELETE FROM todo WHERE ID=?', [id],
     tx.executeSql('DELETE FROM todo WHERE ID=?', &#91;id&#93;,
         loadTodoItems, html5rocks.webdb.onError);
         loadTodoItems, html5rocks.webdb.onError);
   });
   });
Line 139: Line 161:
* http://dev.w3.org/html5/webdatabase/
* http://dev.w3.org/html5/webdatabase/
* http://html5.jidolstar.com/tag/web%20sql%20databaseo
* http://html5.jidolstar.com/tag/web%20sql%20databaseo

Latest revision as of 01:40, 27 March 2026

개요

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

브라우저 지원

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

Indexed Database

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

대안으로 떠오르고 있다

특징

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

사용법

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

, readTransaction

변수 선언

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

열기

  • 사용전에 반드시 데이터 베이스를 열어야 한다.
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);
}

테이블 생성

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)', []);
  });
}

테이블에 데이터 추가

  • 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);
    });
}

검색 질의

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

결과 표시

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>';
}

데이터 지우기

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

hooking it all up

init

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

<body onload="init();">

adding

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

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

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")');
});

참고