Question

I am using Phonegap and I am following the guide on their site but it gives me this function.

function populateDB(tx) {
 tx.executeSql('DROP TABLE IF EXISTS DEMO');
 tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
 tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
 tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
function errorCB(err) {
    alert("Error processing SQL: "+err.code);
}

function successCB() {
    alert("success!");
}

var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);

But how would I pass values as a parameter in there? Is it possible to do something like this?

function populateDB(tx, values) {
 tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
 tx.executeSql('INSERT INTO DEMO (id, data) VALUES (values['id'], values['data'])');
}

var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB(values), errorCB, successCB);

I saw that it is possible to work with question marks but I can't find a clear tutorial on it.

Was it helpful?

Solution

I think this is what you're after -

var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
var insertValues = {
    values1: [1, 'First row'],
    values2: [2, 'Second row']
};

doInserts(insertValues);

function doInserts(insertValues) {
    db.transaction(function(tx) {
        tx.executeSql('DROP TABLE IF EXISTS DEMO');
        tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
        tx.executeSql(
            'INSERT INTO DEMO (id, data) VALUES (?, ?)', 
            insertValues.values1,
            insertSuccess,
            insertFail
        );
        tx.executeSql(
            'INSERT INTO DEMO (id, data) VALUES (?, ?)',
            insertValues.values2,
            insertSuccess,
            insertFail
        );
    });
}

function insertSuccess() {
    console.log('insert success');
}

function insertFail(err) {
    console.log('insertFail, err.message: ' + err.message);
}

This stuff is asynchronous so if you want to know when all your inserts are finished one trick that works is to -

  1. Count the number of inserts you are expecting to do and store it in a variable.
  2. When an insert is successful, decrement 1 on the variable storing the number of inserts expected.
  3. When the variable holding the number of inserts expected is 0 then you know all your inserts have finished.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top