Snapcount
Snapcount

Reputation: 73

Unable to read SQLite DB with jQuery

I am currently developing a web-app in which i am using a SQLite database. I can create the database, and write information into it, but I am unable to use the stored information later in my code.

Here is the code I'm using to read from the database:

function GetItemFromDB(request, level, callback) {
DB.transaction(
        function (transaction) {
            transaction.executeSql(
                'SELECT ? FROM levels WHERE id=?;',
                [request, level], function (transaction, results) {
                    callback(results);
                });
        }
);

}

then I want to use the stored information to create a level in a game. I do this like so:

var ptop = GetItemFromDB('ptop', level);

where ptop is the row containing the information i want, and level is the current level in the game,

So my question is: how can I load storen information from the database, and use it later in the code?

Thanks for your time :)

Upvotes: 0

Views: 2221

Answers (1)

corteggo
corteggo

Reputation: 46

I think you are trying to get a return value by using the asynchronous WebSQL API, so you will never receive a return value from the function GetItemFromDB.

If you want to read data asynchronously from your DB object, you should try something like this:

function GetItemFromDB(request, level, callback) {
    DB.transaction(function(tx){
        tx.executeSql('SELECT ' + request + ' FROM levels WHERE id = ?', [level], function(tx, results){
            callback(results);
        }, errDB);
    }, errDB);
}

function errDB(err) {
    console.log("Error processing SQL: " + err.code);
}

function getItemCallback(results)
{
    alert("Result rows length: " + results.rows.length);

    //result.rows are the results from the SQL
    //if you know the are only one result, you can
    //work with results.rows.item(0), else iterative over rows
    alert("ptop column of row: " + results.rows.item(0).ptop);
}

And then simply call the function:

GetItemFromDB('ptop', level, getItemCallback);

If you want or need to use Synchronous API, I think this link can be helpful for you: http://www.w3.org/TR/webdatabase/#synchronous-database-api

Upvotes: 2

Related Questions