0

I'm building a cordova project in which I have created a database The database includes a table for which I want to insert ID column for table when window is loaded... The problem I'm facing is every time I load the page same ID's are getting inserted...... And I want to insert only once after that whenever I load the page ID's must not get inserted .... Code is given below

window.onload = function(){
db = openDatabase('Timetable', '1.0', 'Time Table', 10 * 1024 * 1024);

db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS schedule(ID INT PRIMARY KEY NOT NULL,monday TEXT,tuesday TEXT,wednesday TEXT,thursday TEXT,friday TEXT,saturday TEXT,sunday TEXT)');
for (var i=1;i<=24;i++){
   tx.executeSql('INSERT INTO schedule(ID) VALUES(?)',[i]);  
}

}

Output : Output of database Output of database

1 Answers1

0

I think this is not a problem about cordova or javascript, but rather a pure logic problem.

What you need to do is check if the schedule table exists (or if the IDs are already in the table), and if it does not add your 24 IDs. See How do I check in SQLite whether a table exists? for reference.

Something like this

window.onload = function() {
  db = openDatabase('Timetable', '1.0', 'Time Table', 10 * 1024 * 1024);

  // Check for schedule table presence with something like this
  // SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';
  // NOTE : I have not tested this code syntax. This is just to give you the idea, I don't know how to write correctly sqlite commands.
  var isScheduleCreated = false;
  db.transaction((tx) => {
    var result = tx.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name='schedule'");
    if (result) isScheduleCreated = true;
  });

  if (isScheduleCreated === false) {
    db.transaction(function (tx) {
      tx.executeSql('CREATE TABLE IF NOT EXISTS schedule(ID INT PRIMARY KEY NOT NULL,monday TEXT,tuesday TEXT,wednesday TEXT,thursday TEXT,friday TEXT,saturday TEXT,sunday TEXT)');
      for (var i=1;i<=24;i++) {
         tx.executeSql('INSERT INTO schedule(ID) VALUES(?)',[i]);  
      }
    }
  }
}

Remarks

db.transaction((tx) => {
  // ...
}

uses arrow functions to define the function, but it is exactly the same as writing it like this. It's just easier and a habit of mine.

db.transaction(function(tx) {
  // ...
}
A Charron
  • 358
  • 1
  • 8