【问题标题】:communicating with database in node.js在 node.js 中与数据库通信
【发布时间】:2023-03-17 18:21:01
【问题描述】:

我是 node.js 的新手。我使用 node.js 创建了服务器端应用程序。在这个应用程序中,我正在从数据库中检索数据。我有以下代码:

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);

    });


});

});

这段代码只返回数据库的第一行作为控件在 res.send(str) 之后返回。我想要 json 格式的 iOS 应用程序中的数据。请就这个问题提出一些解决方案。

【问题讨论】:

    标签: javascript ios node.js


    【解决方案1】:

    类似

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

    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);
            });
        });
    });
    

    应该可以正常工作,具体取决于“行”对象是否简单。

    【讨论】:

    • @VXtreme 当你循环遍历一个数组时,你会得到索引。我刚刚将返回的索引命名为“rowidx”。然后要访问数组中的该元素,您可以执行 rows[rowidx].
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    相关资源
    最近更新 更多