开发者

Inserting related data using SQLite with Blackberry Webworks

开发者 https://www.devze.com 2023-02-12 20:01 出处:网络
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 wit

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.

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.

db.transaction(function(tx) {
     for(var i = 0; i < 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)
}

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.

Is there a better way of doin开发者_如何学JAVAg this?


There are many ways to resolve this problem. A straightforward approach:

db.transaction(function(tx) {
     var eventIds = [];
     for(var i = 0; i < eventsArray.length; i++) {
tx.executeSql("INSERT INTO event(id,eventName,venueName) VALUES (?,?,?)", [null, eventsArray[i].eventName, eventsArray[i].venueName], function(tx,result) { //success callback eventIds[i] = result.insertId; } ); } //for //now, for every event eventsArray[i] you have eventId as eventIds[i] for(i = 0; i < flightsArray.length; i++) { //use eventIds[i] here } });

It would be more appropriate to store id in the callback as eventsArray[i].id = result.indsertId; i.e. directly on the current event object. But it depends on the details of your business logic, maybe event.id already means something else. Also, it makes sense to use local variable for the event so you do not re-calculate eventsArray[i] every time you access its members.

0

精彩评论

暂无评论...
验证码 换一张
取 消