繁体   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