lundi 14 mars 2016

Javascript SQLite Query - Callback the output of executeSql

Having mastered dropping, creating and inserting data into databases I'm now trying to get data out of it using SELECT.

How can I edit my code to be able to use the results of my SELECT query in the body of my file? At the moment I am getting the error that 'callback is not a function' and that variable results is not defined.

I was wanting the query to run, and then callback the output into the 'results' variable so I could access the information using results.id, results.WOdate and results.WOtype.

I've tried to follow a few tutorials, but I am struggling to get this quite right.

////////////////////////////////
//  Functions
////////////////////////////////

// SQL query function
function queryRunner(input, callback) {

    // Needs to be in .transaction to work
    database.transaction(
        function( transaction ){

            // SQL Query
            transaction.executeSql(input);

        },function(err){

            console.log('errorCB: ' + err.code + '; Message: ' + err.message);

        },function( transaction, results ){

            console.log('queryRunner success!');

            // Callback the data set
            callback(results);

        }
    ); // end database.transaction

} // End queryRunner


////////////////////////////////
//  Testing
////////////////////////////////


    var databaseOptions = {
        fileName: "sqlite_WAtest",
        version: "1.0",
        displayName: "SQLite WA Test",
        maxSize: 1024
    }; // End databaseOptions



    var database = openDatabase(
        databaseOptions.fileName,
        databaseOptions.version,
        databaseOptions.displayName,
        databaseOptions.maxSize
    ); // End database

    queryRunner('DROP TABLE WORKOUTS');

    queryRunner('CREATE TABLE IF NOT EXISTS WORKOUTS (id INTEGER PRIMARY KEY AUTOINCREMENT, WOdate TEXT, WOtype TEXT);');

    queryRunner('INSERT INTO WORKOUTS (WOdate, WOtype) VALUES ("Test 1","Test 2")');

    queryRunner('INSERT INTO WORKOUTS (WOdate, WOtype) VALUES ("Test 3","Test 4")');

    queryRunner('SELECT * FROM WORKOUTS');

    alert(results.id);

Aucun commentaire:

Enregistrer un commentaire