node.js中的Mysql动态查询

时间:2013-11-25 07:36:43

标签: mysql node.js

我是这个node.js概念的新手。我尝试过更新数据库并从数据库中检索数据(正常工作)。在进一步的步骤中,我将输出(从数据库)返回到“JSON”格式(工作)好的..现在我的要求是动态查询..

考虑:

以下网址:

http://xxx.xxx.xx.x:3002/users will retrieve all datas from users table and return in json format

但我想要的是:

http://xxx.xxx.xx.x:3002/users=abcdef so the datas for that particular user should be returned in json format.

我的代码:

app.get('/users', function (req, res) {
    connection.query('select * from nodejs where', function(err, rows, fields) {
        res.writeHead(200, { 'Content-Type': 'application/json'});
        res.end(JSON.stringify(rows));
        //res.render('users', {users: docs});
    });
});

那么如何修改上面的代码才能检索特定用户的详细信息..帮我解决这个问题..提前谢谢..

1 个答案:

答案 0 :(得分:0)

在您的应用中创建新路线。您可以在URL中指定参数

http://xxx.xxx.xx.x:3002/users/fname1

此处fname1是用户ID,您可以添加以下代码以从url

获取参数
req.params.fname

此处fname的名称来自您在应用程序中定义的路由:

app.get('/users/:fname', function (req, res) {
connection.query("select * from nodejs where fname= '"+req.params.fname+"'", function(err, rows, fields) {
res.writeHead(200, { 'Content-Type': 'application/json'});
            res.end(JSON.stringify(rows));
//res.render('users', {users: docs});
});
});

使用url /:nameOfParameter为url

中的值指定名称