填充数据库表中返回的JSON [英] Populating a database table with returned JSON

查看:146
本文介绍了填充数据库表中返回的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找存储从一个Drupal网站上的一些JSON内容到数据库表中的某个PhoneGap的应用程序。我使用Ajax来做到这一点。当我运行下面的code和检查表,有人告诉我,这是空的。有谁知道我能填写此表?

  $('#newDiv)。住(pageshow',函数(){

    功能queryDB(德克萨斯州){
        tx.executeSql(SELECT * FROM表A',[],querySuccess,errorCB);
    }

    功能querySuccess(德克萨斯州,结果){
        VAR的len = results.rows.length;
        警报(表+ len的。被发现行+);
        }
    }

    功能CREATETABLE(德克萨斯州){

        tx.executeSql(DROP TABLE IF EXISTSTABLEA');
        VAR SQL =CREATE TABLE IF NOT EXISTSTABLEA(ID INTEGER PRIMARY KEY AUTOINCREMENT,一步VARCHAR(50),文本VARCHAR(50));
        tx.executeSql(SQL,[],successCB,errorCB);
    }

    db.transaction(CREATETABLE,errorCB,successCB);

   $阿贾克斯({
        网址:myURL,
        类型:'后',
        数据:'TID = 4',
        数据类型:JSON,
        错误:函数(XMLHtt prequest,textStatus,errorThrown){
            警报('new_page_node_view  - 无法检索页面节点');
            的console.log(JSON.stringify(XMLHtt prequest));
            的console.log(JSON.stringify(textStatus));
            的console.log(JSON.stringify(errorThrown));
        },
        成功:功能(数据){

            $每个(数据,功能(node_index,node_value){
               db.transaction(函数(德克萨斯州){
                       tx.executeSql(INSERT INTOTABLEA(步,文本)VALUES(,)?,[node_value.title,node_value.body]);
               });
            });
          }
      });

    db.transaction(queryDB,errorCB,successCB);


});
 

解决方案

嘿tipssch试试这个 -

  VAR numInserts = 0;

  $阿贾克斯({
        网址:myURL,
        类型:'后',
        数据:'TID = 4',
        数据类型:JSON,
        错误:函数(XMLHtt prequest,textStatus,errorThrown){
            警报('new_page_node_view  - 无法检索页面节点');
            的console.log(JSON.stringify(XMLHtt prequest));
            的console.log(JSON.stringify(textStatus));
            的console.log(JSON.stringify(errorThrown));
        },
        成功:功能(数据){
            numInserts = data.length; //刀片NUM预期(假设数据为对象的数组)

            $每个(数据,功能(node_index,node_value){
               db.transaction(函数(德克萨斯州){
                       tx.executeSql(INSERT INTOTABLEA(步,文本)VALUES(?,?),[node_value.title,node_value.body]
                       功能(德克萨斯州,结果){
                            numInserts--; //递减1从刀片的预期NUM
                            如果(numInserts == 0){
                                db.transaction(queryDB,errorCB,successCB);
                            }
                       },
                       功能(德克萨斯州,ERR){
                        的console.log(插入错误);
                        如果(ERR){
                            执行console.log(ERR);
                        }
                       });
               });
            });
        }
  });
 

/更新 - 回答为什么上面的方法是必要的。

好了,你可能会问,为什么你不只是叫 queryDB 马上在AJAX调用成功回调的$。每次循环后,像这样的下方 -

  $。阿贾克斯({
        网址:myURL,
        类型:'后',
        数据:'TID = 4',
        数据类型:JSON,
        错误:函数(XMLHtt prequest,textStatus,errorThrown){
            警报('new_page_node_view  - 无法检索页面节点');
            的console.log(JSON.stringify(XMLHtt prequest));
            的console.log(JSON.stringify(textStatus));
            的console.log(JSON.stringify(errorThrown));
        },
        成功:功能(数据){
            $每个(数据,功能(node_index,node_value){
               db.transaction(函数(德克萨斯州){
                    tx.executeSql(INSERT INTOTABLEA(步,文本)VALUES(,)?,[node_value.title,node_value.body]);
               });
            });
            db.transaction(queryDB,errorCB,successCB); //<  - 刀片不能当这个被调用全部完成
        }
   });
 

让我们假设你有1000条记录,你会从你的JSON结果插入。 在AJAX调用的成功;当你调用 db.transaction(queryDB,errorCB,successCB)这些插入就不会完成。您必须实现一个成功的回调到你的 tx.executeSql 插入知道什么时候插入已完成。

我所做的,而不是在我的第一种方法上面将使所有插入到全面完成调用 queryDB 函数之前。我增加了一个在线的成功和失败回调至 tx.executeSql(INSERT INTOTABLEA(步,文本)VALUES(,)?,[node_value.title,node_value.body]); 。我总是建议做这行任何的PhoneGap您WebSQL的(他们没有被行内任一)。

我做了我的previous作业过程中广泛WebSQL交易PhoneGap的。这在很大程度上涉及到通过JSON循环和将其写入本地数据库表。当你有很多插入,并试图找出刚刚写入之前通知用户或者在您的案件拉低数据的是,当他们都完全做到了出现真正困难的问题。

那么,秘诀您将学习如何做插入的情况下 -

  
      
  1. 计数插入你的期望来执行,并将其存储在一个变量的数量。
  2.   
  3. 在成功回调的 tx.executeSql 将减1的变量包含您所期望的插入的数目。
  4.   
  5. 当变量到达0中的 tx.executeSql 成功的回调,那么你知道你所有的刀片已经完成。
  6.   

简单的例子1插入 -

  //错误的做法在这里
db.transaction(函数(德克萨斯州){
    tx.executeSql(INSERT INTOTABLEA(步,文本)VALUES(,)?,[富,酒吧]);
    //它将启动选择查询中的插入完成之前,
    tx.executeSql(SELECT * FROM表A',[],querySuccess,errorCB);
});

//正确的方法在这里
db.transaction(函数(德克萨斯州){
    tx.executeSql(INSERT INTOTABLEA(步,文本)VALUES(,)?,[富,酒吧],insertDone,insertFail);
});

功能insertDone(德克萨斯州,结果){
    //插入完成后,现在你可以运行queryDB
    tx.executeSql(SELECT * FROM表A',[],querySuccess,errorCB);
}

功能insertFail(德克萨斯州,ERR){
    的console.log(插入错误);
    如果(ERR){
        执行console.log(ERR);
    }
}
 

我希望这可以帮助解释,为什么我用第一种方法,而不是仅仅运行 queryDB 在AJAX调用成功的回调。

我希望这一切都将帮助别人的未来,笑。

I'm looking to store some JSON content from a Drupal website to a database table in a PhoneGap app. I am using ajax to do this. When I run the following code and check the table, I am told that it is empty. Does anybody know how I could populate this table?

$('#newDiv').live('pageshow',function(){

    function queryDB(tx) {
        tx.executeSql("SELECT * FROM 'tableA'", [], querySuccess, errorCB);
    }

    function querySuccess(tx, results) {
        var len = results.rows.length;
        alert("Table: " + len + " rows were found.");
        }
    }

    function createTable(tx) {

        tx.executeSql('DROP TABLE IF EXISTS "tableA"');
        var sql = "CREATE TABLE IF NOT EXISTS 'tableA' (id INTEGER PRIMARY KEY AUTOINCREMENT, step VARCHAR(50), text VARCHAR(50))";
        tx.executeSql(sql, [], successCB, errorCB); 
    }

    db.transaction(createTable, errorCB, successCB);

   $.ajax({
        url: myURL,
        type: 'post',
        data: 'tid=4',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('new_page_node_view - failed to retrieve page node');
            console.log(JSON.stringify(XMLHttpRequest));
            console.log(JSON.stringify(textStatus));
            console.log(JSON.stringify(errorThrown));
        },     
        success: function (data) {

            $.each(data, function (node_index,node_value) {
               db.transaction(function(tx){
                       tx.executeSql("INSERT INTO 'tableA' (step, text) VALUES (?, ?)",[node_value.title, node_value.body]);
               });
            });
          }
      });

    db.transaction(queryDB, errorCB, successCB);


});

解决方案

Hey tipssch try this -

  var numInserts = 0;

  $.ajax({
        url: myURL,
        type: 'post',
        data: 'tid=4',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('new_page_node_view - failed to retrieve page node');
            console.log(JSON.stringify(XMLHttpRequest));
            console.log(JSON.stringify(textStatus));
            console.log(JSON.stringify(errorThrown));
        },     
        success: function (data) {
            numInserts = data.length; // num of inserts to expect (assumes data is in array of objects)

            $.each(data, function (node_index,node_value) {
               db.transaction(function(tx){
                       tx.executeSql("INSERT INTO 'tableA' (step, text) VALUES (?, ?)",[node_value.title, node_value.body],
                       function(tx, results){
                            numInserts--; // decrement 1 from expected num of inserts
                            if (numInserts == 0){
                                db.transaction(queryDB, errorCB, successCB);
                            }
                       }, 
                       function(tx, err){
                        console.log("insert error");
                        if (err){
                            console.log(err);
                        }
                       });
               });
            });
        }
  });

/Update - Answering why the above approach is necessary.

Ok, so you might wonder why you don't just call queryDB right away in the success callback of the AJAX call after your $.each loop, like this below -

   $.ajax({
        url: myURL,
        type: 'post',
        data: 'tid=4',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('new_page_node_view - failed to retrieve page node');
            console.log(JSON.stringify(XMLHttpRequest));
            console.log(JSON.stringify(textStatus));
            console.log(JSON.stringify(errorThrown));
        },     
        success: function (data) {
            $.each(data, function (node_index,node_value) {
               db.transaction(function(tx){
                    tx.executeSql("INSERT INTO 'tableA' (step, text) VALUES (?, ?)",[node_value.title, node_value.body]);
               });
            });
            db.transaction(queryDB, errorCB, successCB); // <-- the inserts could not all be finished when this gets called
        }
   });

Let's say you have 1000 records you are going to insert from your JSON result. These inserts will not be finished when you call db.transaction(queryDB, errorCB, successCB); in the success of the AJAX call. You must implement a success callback to your tx.executeSql insert to know when an insert has finished.

What I did instead in my first approach above will allow for all the inserts to be fully completed before you call the queryDB function. I added an inline success and fail callback to the tx.executeSql("INSERT INTO 'tableA' (step, text) VALUES (?, ?)",[node_value.title, node_value.body]);. I always suggest doing this for any of your WebSQL in PhoneGap (they don't have to be inline either).

I did extensive WebSQL transactions in PhoneGap during my previous job. Much of this involved looping through JSON and writing it into local database tables. The real difficult issue occurs when you have many inserts and trying to figure out when they are all completely done before notifying the user or in your case pulling the data out that was just written.

So... the trick you will learn to do in the case of inserting is -

  1. Count the number of inserts your are expecting to perform and store it in a variable.
  2. In the success callback of your tx.executeSql insert subtract 1 from your variable that holds the number of inserts you are expecting.
  3. Once the variable gets to 0 in the tx.executeSql success callback then you know all of your inserts have finished.

Simple example with 1 insert -

// wrong approach here
db.transaction(function(tx){
    tx.executeSql("INSERT INTO 'tableA' (step, text) VALUES (?, ?)",["foo", "bar"]);
    // it will start the select query before the insert has completed
    tx.executeSql("SELECT * FROM 'tableA'", [], querySuccess, errorCB);
});

// the right approach here
db.transaction(function(tx){
    tx.executeSql("INSERT INTO 'tableA' (step, text) VALUES (?, ?)",["foo", "bar"], insertDone, insertFail);
});

function insertDone(tx, results){
    // insert is done, now you can run the queryDB
    tx.executeSql("SELECT * FROM 'tableA'", [], querySuccess, errorCB);
}

function insertFail(tx, err){
    console.log("insert error");
    if (err){
        console.log(err);
    }
}

I hope this helps clarify why I used the first approach instead of just running the queryDB in the success callback of the AJAX call.

Hopefully all this will help someone in the future, lol.

这篇关于填充数据库表中返回的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆