HTML5 Database Operations

I am interested, for example, W3C Offline Web Apps example

function renderNotes() {
  db.transaction(function(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)', 
      []);
    tx.executeSql(‘SELECT * FROM Notes’, [], function(tx, rs) {
      for(var i = 0; i < rs.rows.length; i++) {
        renderNote(rs.rows[i]);
      }
    });
  });
}

has a create table before "main" executeSql(). would it be better if I do something like

$(function() {
    // create table 1st
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)', 
          []);
    });

    // when i execute say to select/modify data, i just do the actual action
    db.transaction(function(tx) {
        tx.executeSql(‘SELECT * FROM Notes’, [], function(tx, rs) {
            ...
        }
    });

    db.transaction(function(tx) {
        tx.executeSql(‘INSERT ...’, [], function(tx, rs) {
            ...
        }
    });
})

I thought that I do not need to constantly repeat CREATE IF NOT EXISTS?

Update

function initDatabase() {
    notes = openDatabase("todolist", "1.0", "To-Do List", 1*1024*1024, function (notes) {
        notes.changeVersion("", "1.0", function(tx) {
            tx.executeSql("CREATE TABLE todolist (id INTEGER, task TEXT)", [], function(tx, rs) {
                alert("Table created");
            });
        }); 
    })
}
+3
source share
1 answer

You are accessing this with help changeVersion. The API supports database version control, so you can apply schema changes during updates or in your case .. installation.

There are several examples in the documentation :

function prepareDatabase(ready, error) {
  return openDatabase('documents', '1.0', 'Offline document storage', 5*1024*1024, function (db) {
    db.changeVersion('', '1.0', function (t) {
      t.executeSql('CREATE TABLE docids (id, name)');
    }, error);
  });
}

prepareDatabase, , < 1.0 , , CREATE TABLE.

, .. 1.0, changeVersion , CREATE TABLE.

+2

Source: https://habr.com/ru/post/1748347/


All Articles