■ 웹 SQL 데이터베이스에서 테이블 데이터를 추가/삭제/조회하는 방법을 보여준다.
▶ test.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script language="javascript"> var db; function onLoad() { try { this.db = openDatabase('html5', '1', '전화번호부', 1024 * 1024); } catch(e) { document.getElementById('output').innerHTML = '데이터베이스를 여는 중 에러가 발생했습니다 : ' + e; return; } document.getElementById('output').innerHTML = '데이터베이스를 열었습니다.'; } function createCallback(tx) { tx.executeSql('create table phonebook (id integer primary key autoincrement, name varchar(32), phone varchar(32))'); } function errorCallback(tx) { document.getElementById('output').innerHTML = '테이블 생성시 에러가 발생했습니다.'; } function successCallback(tx) { document.getElementById('output').innerHTML = '테이블을 생성했습니다.'; } function createTable() { this.db.transaction(createCallback, errorCallback, successCallback); } function dropTable() { this.db.transaction ( function(tx) { tx.executeSql('drop table phonebook'); document.getElementById('output').innerHTML = '테이블을 삭제했습니다.'; } ); } function insertData() { var name = document.getElementById('name' ).value; var phone = document.getElementById('phone').value; this.db.transaction ( function(tx) { tx.executeSql('insert into phonebook (name, phone) values (?, ?)', [name, phone]); } ); document.getElementById('output').innerHTML = '데이터를 추가했습니다.'; document.getElementById('name' ).value = ''; document.getElementById('phone').value = ''; } function removeData(id) { this.db.transaction ( function(tx) { tx.executeSql('delete from phonebook where id = ?', [id]); } ); document.getElementById('output').innerHTML = '데이터를 삭제했습니다.'; } function showData() { var message = ''; this.db.transaction ( function(tx) { tx.executeSql ( 'select * from phonebook', [], function(tx, rs) { for(var i = 0; i < rs.rows.length; i++) { var row = rs.rows.item(i); message = message + row['name'] + ', ' + row['phone'] + ', ' + '<a href="javascript:removeData(' + row['id'] + ');">삭제</a><br />'; } document.getElementById('output').innerHTML = message; } ); } ); } </script> </head> <body onload="onLoad();"> <div id="output">데이터베이스 테스트입니다.</div> <p /> <input type="button" value="테이블 생성" onclick="createTable();" /> <input type="button" value="테이블 삭제" onclick="dropTable();" /> <p /> 이름 : <input type="text" id="name" size="10" /> 전화 : <input type="text" id="phone" size="10" /> <input type="button" value="데이터 추가" onclick="insertData();" /> <input type="button" value="데이터 조회" onclick="showData();" /> </body> </html> |