简体   繁体   中英

communicating with database in node.js

I am new to the node.js . I have created server side application by using node.js. In this application i am retrieving the data from the database . I have following code for this:

router.map(function () {
this.root.bind(function (req, res) {  
db.all("SELECT * FROM employee", function(err, rows)
{
    rows.forEach(function(row)
    {
         str=str+' '+row.name+'     '+row.empid+'    '+row.address+'   '+row.mobile;
        res.send(str);

    });


});

});

this code returning me only the first row of the database as control returns after res.send(str). I want data in my iOS app in json format. Please suggest some solution on this problem.

Something like

router.map(function () {
    this.root.bind(function (req, res) {  
        db.all("SELECT * FROM employee", function(err, rows)
        {
            res.send(JSON.stringify(rows));
        });
    });
});

OR

router.map(function () {
    this.root.bind(function (req, res) {  
        db.all("SELECT * FROM employee", function(err, rows)
        {
            var out = [];
            var rowidx;
            for(rowidx in rows) {
                out.push({name: rows[rowidx].name, empid: rows[rowidx].empid, address: rows[rowidx].address, mobile: rows[rowidx].mobile}); 
            }
            res.send(JSON.stringify(out);
        });
    });
});

Should work fine, depending on whether the "rows" object is simple or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM