1

I am trying to avoid populate the database if the database exists but when I try to cancel this line in my code I get "Error processing SQL:1"

tx.executeSql('DROP TABLE IF EXISTS DEMO');

this is my whole populate function

 function populateDB(tx) {
        tx.executeSql('DROP TABLE IF EXISTS DEMO');
        tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, word TEXT NOT NULL');
        tx.executeSql('INSERT INTO DEMO (id, word) VALUES ("1", "Apple")');
        tx.executeSql('INSERT INTO DEMO (id, word) VALUES ("2", "Orange")');

    }
shoujo_sm
  • 3,173
  • 4
  • 37
  • 60

2 Answers2

6

Why dont you use

CREATE TABLE IF NOT EXISTS DEMO  (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, kword TEXT NOT NULL, eword TEXT NOT NULL, pronoun TEXT NOT NULL, level INTEGER NOT NULL)
skhurams
  • 2,133
  • 7
  • 45
  • 82
2

Your function has set of issues which are corrected below. It should work now.

    function populateDB(tx) {
        isTableExists(tx, "DEMO", function(status) {
            if (!status) {
                alert("table not exist, creating one");
                tx.executeSql('CREATE TABLE DEMO (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, kword TEXT NOT NULL, eword TEXT NOT NULL, pronoun TEXT NOT NULL, level INTEGER NOT NULL)');
                tx.executeSql('INSERT INTO DEMO (kword, eword, pronoun, level) VALUES ("Apple", "", "", 1)');
                tx.executeSql('INSERT INTO DEMO (kword, eword, pronoun, level) VALUES ("Orange", "", "", 2 )');
            } else {
                alert("table exist, dropping for test");
                tx.executeSql('DROP TABLE DEMO');
            }
        });
    }

    function isTableExists(tx, tableName, callback) {
        tx.executeSql('SELECT * FROM DEMO', [], function(tx, resultSet) {
            if (resultSet.rows.length <= 0) {
                callback(false);
            } else {
                callback(true);
            }
        }, function(err) {
            callback(false);
        });
    }
dhaval
  • 7,611
  • 3
  • 29
  • 38
  • hi, I edited the question (some mistake when I write question for the SQL) when I left out the "id" from "INSERT INTO DEMO (id, word)" I get Error processing SQL:5. I am trying not to execute insert SQL if table DEMO exist. – shoujo_sm Jul 02 '12 at 02:57
  • sorry but i dont understand your question now, do you want to create table everytime you run the application?? – dhaval Jul 02 '12 at 03:41
  • I only want to create table one time and all those entry execute again every time I load the pages again. – shoujo_sm Jul 02 '12 at 04:15
  • so you want to create tables only once, and put data also only once?? – dhaval Jul 02 '12 at 04:17
  • Yup. I just want to set up all the table entries once which is at the beginning of applications install only. – shoujo_sm Jul 02 '12 at 04:19