簡體   English   中英

使用SQLite和Blackberry Webworks插入相關數據

[英]Inserting related data using SQLite with Blackberry Webworks

我有一個在BB5下運行的Blackberry Webworks Web應用程序,使用SQLite數據庫在本地存儲數據。 該數據庫有兩個表,即事件和排期,其中一個事件可以具有與其關聯的許多排期。

我發現很難弄清楚如何從一組數據中填充兩個表。 我的麻煩是由於BB的SQLite實現的異步方式,使外鍵插入到flight表中。

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)
}

因此,似乎無論我在哪里嘗試對航班執行插入查詢,我都會丟失一部分數據。 包含我需要插入的廣告投放的插入ID或實際事件對象。

有更好的方法嗎?

有很多方法可以解決此問題。 一種簡單的方法:

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 } });

將id存儲在回調中會更合適,例如eventsArray [i] .id = result.indsertId;。 即直接在當前事件對象上。 但這取決於您的業務邏輯的細節,也許event.id已經包含其他含義。 同樣,對事件使用局部變量是有意義的,因此您不必在每次訪問其成員時都重新計算eventsArray [i]。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM