SQL Lite Querying, build an object with multiple results

2 posts, 0 answers
  1. Steve
    Steve avatar
    7 posts
    Member since:
    Oct 2013

    Posted 30 Oct 2013 Link to this post

    I'm trying to build an object with multiple sqlite result sets, something along the lines of

    table1 = result of ("SELECT * FROM table1");
    table2 = result of ("SELECT * FROM table2");
    table3 = result of ("SELECT * FROM table3");
    table4 = result of ("SELECT * FROM table4");

    var obj = {
    'table1': table1,
    'table2': table2,
    'table3': table3,
    'table4': table4, 
    };

    This seems like such a simple task yet can't find any examples of it anywhere. Everything is always one query at a time then calling a callback function to handle the single set of results.

    Any help much appreciated.

  2. Ivan
    Admin
    Ivan avatar
    111 posts

    Posted 04 Nov 2013 Link to this post

    Hi,

    Perhaps the simplest approach to combine results from different queries is to use nested callbacks:

    db.transaction(function(tx) {
        tx.executeSql("select * from table1", [],
            function(tx, rs1) {
                tx.executeSql("select * from table2", [],
                    function(tx, rs2) {
                        var obj = {
                            rows1: rs1.rows,
                            rows2: rs2.rows
                        };
                    });
            });
    });

    This works, however if you need to execute many queries, the code can quickly become cumbersome.
    A better approach, which does not require such nesting of callbacks is to use jQuery Deffered Object:

    db.transaction(function(tx) {
        var q1 = executeQuery(tx, "select * from table1");
        var q2 = executeQuery(tx, "select * from table2");
     
        $.when(q1, q2)
         .done(function(rs1, rs2) {
            var obj = {
                rows1: rs1.rows,
                rows2: rs2.rows
            };
        });
    });
     
    function executeQuery(tx, q) {
        var d = $.Deferred();
         
        tx.executeSql(q, [],
            function (tx, rs) {
                d.resolve(rs);
            },
            function (tx, e) {
                d.reject(e);
            });
         
        return d.promise();
    }

    Hope this helps.

    Regards,
    Ivan
    Telerik
    You've missed the Icenium Visual Studio Integration keynote? It has been recorded and posted here.
    Looking for tips & tricks directly from the Icenium team? Check out our blog!
    Share feedback and vote for features on our Feedback Portal.
Back to Top