简体   繁体   中英

Inserting related data using SQLite with Blackberry Webworks

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 doing 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; ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM