title: Inserting related data using SQLite with Blackberry Webworks
body: <p>I have a Blackberry Webworks webapp running under BB5, storing data locally using a SQLite database. The database has two tables, event and flight, where one event can have many flights associated with it.</p>
  
  <p>I'm finding it difficult to work out how to populate both tables from an array of data. My trouble is in getting the foreign key to insert into the flights table, due to the asynchronous way that BB's SQLite implementation works.</p>
  
  <pre><code>db.transaction(function(tx) {
       for(var i = 0; i &lt; eventsArray.length; i++) {
            var insertId = 0;
            tx.executeSql("INSERT INTO event(id,eventName,venueName) VALUES (?,?,?)",
                              [null,
                               eventsArray[i].eventName,
                               eventsArray[i].venueName],
                               function(tx,result) { //success callback
                                   insertId = result.insertId;
                                   //If I try inserting flights here, eventsArray[i] always returns
                                   //the last item in the array, the for loop has kept running
                               }
             );
             //If I try inserting here, I don't have the insertId
             //to populate the foreign key (still set to 0 as the
             //callbacks haven't fired yet)
  }
  </code></pre>
  
  <p>So it seems wherever I try to perform the insert query for the flights, I'm missing a piece of data. Either the insert ID or the actual event object containing the flights I need to insert.</p>
  
  <p>Is there a better way of doing this?</p>