使用循环向sqlite数据库添加行(Phonegap)

4
我创建了一个小的Phonegap应用程序,通过XML的Ajax调用获取新闻数据。这个工作很好,但我想将数据存储在数据库表中,以便也可以离线阅读新闻。
因此,当Ajax回调循环遍历数据时,我使用它填充了一个全局新闻对象,然后调用一个函数来检查数据是否已经存储在数据库中。如果没有,应将其插入到新闻表中。
问题是,在将新闻存储在表中的事务中,似乎我的新闻对象不再存在,因为我收到了以下消息:
“Uncaught TypeError:Cannot read property 'title' of undefined in ...”
那么我该如何确保它能正常工作呢?这里是我选择新闻并想要检查它是否已经存在的部分代码:
//  Check if a news from the internet already exists in the database; If not, insert it
function checkNewsInDB(){
    db.transaction(function(tx){
        tx.executeSql("SELECT * FROM NEWS", [], checkSuccess, dbErrorCB);
    }, dbErrorCB, dbSuccessCB);
}

//  Result Callback from the News Check
function checkSuccess(ctx, result){
    var len = result.rows.length;
    var found = false;
    for(var n = 0; n < newsContainer.length; n++){
        for(var r = 0; r < len; r++){
            if(result.rows.item(r).n_title == newsContainer[n].title 
               && result.rows.item(r).n_pubdate == newsContainer[n].pubdate){
                found = r;
            }
        }
        if(found == false){
            db.transaction(function(tx){
                tx.executeSql("INSERT INTO NEWS (n_title, n_link, n_creator, n_pubdate, n_description) VALUES (?,?,?,?,?)", [newsContainer[n].title, newsContainer[n].link, newsContainer[n].creator, newsContainer[n].pubdate, newsContainer[n].description], insertSuccess, dbErrorCB);
            }, dbErrorCB, dbSuccessCB);
        } else {
            found = false;
        }
    }
}

新闻容器已经填充了几行数据,我已经检查过了。如果有人能帮我理解为什么这不起作用,我会非常高兴。

提前致谢!

问候,

Bernd

2个回答

4

db.transaction 是异步的 - 在 executeSql 执行时,n 已经被递增到循环的末尾。

与其为每个项目创建一个新事务,不如将循环移动到事务函数内部。


你能发一下样例代码吗?我还没弄明白。 - Vivek Singh

2

感谢您的回答。这是适用于所有遇到相同问题的人的代码:

//  Check if a news from the internet already exists in the database; If not, insert it
function checkNewsInDB(){
    db.transaction(function(tx){
        tx.executeSql("SELECT * FROM NEWS", [], checkSuccess, dbErrorCB);
    }, dbErrorCB, dbSuccessCB);
}

//  Result Callback from the News Check
function checkSuccess(ctx, result){
    var len = result.rows.length;
    var found = false;
    for(var n = 0; n < newsContainer.length; n++){
        for(var r = 0; r < len; r++){
            if(result.rows.item(r).n_title == newsContainer[n].title 
               && result.rows.item(r).n_pubdate == newsContainer[n].pubdate){
                found = r;
            }
        }
        if(found == false){
            var title = newsContainer[n].title;
            var link = newsContainer[n].link;
            var creator = newsContainer[n].creator;
            var pubdate = newsContainer[n].pubdate;
            var description = newsContainer[n].description;
            ctx.executeSql("INSERT INTO NEWS (n_title, n_link, n_creator, n_pubdate, n_description) VALUES (?,?,?,?,?)",
                        [title, link, creator, pubdate, description], insertSuccess, dbErrorCB);
        } else {
            found = false;
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接