본문 바로가기

Web

Web Database 사용

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
Web Database는 Webkit 기반의 브라우저에서 동작한다. 현재 WebKit 기반의 브라우저로는 메이저로 크게 2가지가 있는데 Safari , Chrome 이 있다.

WebDB는 Local Storage와는 다른 개념으로 Sqllite를 사용한다고 생각하면 될 것 같다.

Web DB를 사용하기 위하여 간단하게 Class를 만들어보았다.
소스는 다음과 같다.

var WebDB = function(){

	this.conn = null,						// DB Connection

	this.dbName = null,						// DB Name
	this.version = "1.0",					// Version
	this.desciption = "Web Database",		// Description
	this.dbSize = 5 * 1024 * 1024,			// DB Size

	/**
	*	__construct
	*
	*	intiailize WebDB Class
	*	The unit of dbSize is MegaByte.
	*/
	this.init = function(dbName , version , description , dbSize){
		try
		{
			if(window.openDatabase)
			{
				// check parameters
				if(typeof(dbName) != 'string')
				{
					alert('Database Name is required.');
				}
				else
				{
					this.dbName = dbName;
				}
				
				// version check
				if(typeof(version) != 'undefined')
				{
					this.version = version;
				}

				// description check
				if(typeof(description) != 'undefined')
				{
					this.description = description;
				}

				// database size check
				if(typeof(dbSize) != 'undefined')
				{
					this.dbSize = dbSize * 1024 * 1024;
				}

				this.conn = openDatabase(this.dbName , this.version , this.description , this.dbSize);

				if( !this.conn )
					alert('Can\'t connect to database.');				
			}
			else
			{
				alert('Your browser does not support web database.\r\nPlease start from WebKit browser');
			}
		}
		catch (error)
		{
			alert(error.message);
		}
	},

	this.query = function(query , successHandler){

		this.conn.transaction(function(tx){
			try
			{
				tx.executeSql(query , 
								[] , 
								function(tx , result){
									successHandler(result);
								}, 
								function(tx , error){
									alert('Something unexpected happened:' + error.message);
								}
							  );
			}
			catch (error)
			{
				alert(error.message);
			}
		});

	}
}

실제로 사용하는 예제는 다음과 같다.

window.onload = function(){
	var db = new WebDB();
	db.init('test');			// Test란 데이타베이스를 사용. 없으면 생성이 된다.

	// db.init('test' , '1.0' , 'Test 데이타베이스' , 5);		// 5MB의 test 데이타 베이스를 생성, 혹은 사용한다.

	// 쿼리를 실행시켜주고 그 결과를 처리할 callback  함수를 등록한다.
	db.query("SELECT * FROM TB_TEST" , getTbTest);
}

// 결과에 대한 조작을 하는 callback 함수이다.
function getTbTest(result)
{
	var loopCnt = result.rows.length;

	for(int i = 0 ; i < loopCnt ; i++)
	{
		var item = result.rows.item(i);

		alert(item.uid);
		alert(item.writer);
		alert(item.subject);
	}
}