2011-02-23 54 views
0

我有一個運行在BB5下的Blackberry Webworks webapp,使用SQLite數據庫在本地存儲數據。該數據庫有兩個表格,即事件和航班,其中一個事件可以有多個航班與之關聯。使用SQLite和Blackberry插入相關數據Webworks

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

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或包含我需要插入的航班的實際事件對象。

有沒有更好的方法來做到這一點?

回答

0

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

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]。