Matt
Matt

Reputation: 31

SQLite DELETE transaction not working when grabbing value from Array

This is driving me crazy.

I have a message queue that I'm using a local storage web DB to store these messages when the device is offline and when there is an internet connection it sends out these messages. After it sends the messages, I want them deleted from the table.

When I send out the messages I keep an array called MessageIDs that way I can reference what rows need deleted.

I loop through the length of the MessageIDs and grab each ID and have a DELETE transaction. My alert() gets the right value but when the transaction executes, the value is undefined. I tried hard coding a known "ID" into the transaction and it worked. Any thoughts?

 var MessageIDs = new Array();

//In the block of code not shown I populate MessageIDs and send out messages

for(var j=0; j < MessageIDs.length; j++)
{
  alert(MessageIDs[j]); //Pulls the right value
  site.data.database.transaction(  
            function (transaction) {  
                //[MessageIDs[j]] has a value of undefined and thus doesn't get deleted but the transaction doesn't technically fail either
                transaction.executeSql("DELETE FROM Messages WHERE id = ?;", [MessageIDs[j]],  
                    site.contact.removeQueuedMessagesSuccess, site.contact.removeQueuedMessagesError);  
            }  
        ); 
}

Upvotes: 2

Views: 1098

Answers (1)

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20033

Sorry I can't put this as a comment, so here as an answer, extending DCoder's answer: You can also put the loop inside the transaction, then it will work, too. His solution is cleaner, though.

Edit: Maybe I should give a reason for why this addition is not unimportant: Obviously, you can't always combine the queries in such a way. So before you start nesting transactions, just put the loop of queries inside one transaction.

Upvotes: 1

Related Questions