Search code examples
javascriptsqlitecordovavisual-studio-2015cordova-plugins

SQLite plugin Cordova basic code


I'm new to Cordova & Sqlite but I wrote some code and I can't figure out what is wrong with it? Any suggestions? I always get the following output from the Javascript debugger:

Click to see error messages

 <script type="text/javascript">
    // Wait for Cordova to load
    document.addEventListener('deviceready', onDeviceReady, false);
    var output = document.getElementById('outputField');

    // Cordova is ready
    function onDeviceReady() {
        window.sqlitePlugin.openDatabase({ name: 'test.db', location: 2 }, function (db) {
            output.innerHTML += '</br> - Database created/opened';

            db.transaction(function (tx) {
                tx.executeSql(tx, "CREATE TABLE  localStorage2 IF NOT EXISTS (key UNIQUE, value)");
            });


            output.innerHTML += '</br> - Table localStorage2 Created';

            storeValue(db, 'localStorage2', 'testKey', 'testValue');
            output.innerHTML += '</br> - Insert dummy value';

            output.innerHTML += '</br> ' + readValue(db, 'localStorage2', 'testKey');
        });
    }


    function storeValue(db, table, key, value) {
        db.transaction(function (tx) {
            tx.executeSql(tx, 'INSERT INTO ' + table + ' (key,value) VALUES ("' + key + '","' + value + '")');
        });

    }

    function readValue(db, table, key) {
        db.transaction(function (tx) {
            return db.executeSql(tx, 'SELECT * FROM ' + table + ' WHERE key="' + key + '"');
        });
    }
</script>

Solution

  • If you are testing a new plugin, library, … whatever, the best way is to read the docs, play a little bit with the examples and expand it step by step for your needs.

    The SQLite plugin is event driven, that means, that you have to wait until the job is done.

    You are doing it this way and this don't work:

    var the_result = mySQL_Job();
    
    function mySQL_Job(){
       db.readTransaction(function(tx) {   
          return db.executeSql(…);
       });
    }
    

    The right way is:

    mySQL_Job();
    
    function mySQL_Job(some_values){
       tx.executeSql("SELECT * FROM myTable", [], function(tx, res) {
    
          //Here goes your result handling, like inserting values in your html
    
    }, function(error) {
        console.log('SQLite error: ' + error.message);
      });
    }
    

    This you have to do for every sql job, please see the docs at: https://github.com/litehelpers/Cordova-sqlite-storage

    If you have a lot of queries then it is a good idea to use promises: How to compact SQL instructions in Cordova?