database.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var database={};
  2. database.db={};
  3. database.onError = function(tx, e) {
  4. var log = document.createElement('div');
  5. log.setAttribute('name','error');
  6. log.setAttribute('style','background-color:red');
  7. log.innerText = e.message;
  8. document.getElementById('logs').appendChild(log);
  9. }
  10. database.onSuccess = function(tx, r) {
  11. if (r.rows.length) {
  12. var ol;
  13. for (var i = 0; i < r.rows.length; i++) {
  14. ol = document.createElement('ol');
  15. ol.innerHTML = r.rows.item(i).ID + ": " + r.rows.item(i).docname + " (" + r.rows.item(i).created + ")";
  16. document.getElementById('logs').appendChild(ol);
  17. }
  18. }
  19. }
  20. database.open=function(){
  21. database.db=openDatabase('HTML5', '1.0', 'Offline document storage', 100*1024);
  22. }
  23. database.create=function(){
  24. database.db.transaction(function(tx) {
  25. tx.executeSql("CREATE TABLE IF NOT EXISTS docs(ID INTEGER PRIMARY KEY ASC, docname TEXT, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP)",
  26. [],
  27. database.onSuccess,
  28. database.onError);
  29. });}
  30. database.add = function(message) {
  31. database.db.transaction(function(tx){
  32. tx.executeSql("INSERT INTO docs(docname) VALUES (?)",
  33. [message], database.onSuccess, database.onError);
  34. });
  35. }
  36. database.selectAll = function() {
  37. database.db.transaction(function(tx) {
  38. tx.executeSql("SELECT * FROM docs", [], database.onSuccess,
  39. database.onError);
  40. });
  41. }
  42. database.onDeleteAllSuccess = function(tx, r) {
  43. var doc = document.documentElement;
  44. var db_completed = document.createElement("div");
  45. db_completed.setAttribute("id", "db_completed");
  46. db_completed.innerText = "db operation completed";
  47. doc.appendChild(db_completed);
  48. }
  49. database.deleteAll = function() {
  50. database.db.transaction(function(tx) {
  51. tx.executeSql("delete from docs", [], database.onDeleteAllSuccess,
  52. database.onError);
  53. });
  54. }
  55. var log = document.createElement('div');
  56. log.setAttribute('name','notice');
  57. log.setAttribute('style','background-color:yellow');
  58. log.innerText = typeof window.openDatabase == "function" ? "Web Database is supported." : "Web Database is not supported.";
  59. document.getElementById('logs').appendChild(log);
  60. try {
  61. database.open();
  62. database.create();
  63. database.add('Doc 1');
  64. database.add('Doc 2');
  65. database.selectAll();
  66. database.deleteAll();
  67. } catch(error) {
  68. var log = document.createElement('div');
  69. log.setAttribute('name','critical');
  70. log.setAttribute('style','background-color:pink');
  71. log.innerText = error;
  72. document.getElementById('logs').appendChild(log);
  73. }