nodejs mysql返回的_使用nodejs和node-mysql返回行

bd96500e110b49cbb3cd949968f18be7.png

I'm discovering Nodejs and the node-mysql module. I have a small problem. Every tutorial that I find explain how to do a select on the database but they never return the rows, they always log them, which is absolutely useless for my case.

I have a app.js file :

// Get continents

app.get("/continents", function(request, result) {

console.log("Continents : " + database.findAllContinents());

});

And a mysql.js file :

exports.findAllContinents = function(connection) {

var connection = getConnection();

connection.query('select id, code, name from Continent', function (err, rows, fields) {

if (err) {

console.log("Error in findAllContinents : " + err)

}

return JSON.stringify(rows);

});

closeConnection(connection);

};

How can I make the function return the rows to use them in the app.js file ? I don't really want to create connections in the app.js file I want the DAO layer to be separated.

Do you have any idea ?

Also, if someone has an idea of the pros/cons of using node-mysql instead of an ORM (sequelize, persistence.js...)

Thanks

解决方案

query() is an asynchronous function from which you can't return any results. And consequently, any functions which call asynchronous functions themselves (like your findAllContinents) can't either.

Instead, you need to pass a callback function (also explained here) which will be called when the query is done:

// app.js

app.get("/continents", function(request, response) {

database.findAllContinents(function(err, results) {

if (err)

throw err; // or return an error message, or something

else

res.send(results); // as a demo, we'll send back the results to the client;

// if you pass an object to 'res.send()', it will send

// a JSON-response.

});

});

// mysql.js

exports.findAllContinents = function(cb) {

var connection = getConnection();

connection.query('select id, code, name from Continent', function (err, rows, fields) {

// close connection first

closeConnection(connection);

// done: call callback with results

cb(err, rows);

});

};

As for (not) using an ORM, that really depends on the use case. I would choose an ORM (my favorite for MySQL is patio) in case my app requires multiple (complex) models, perhaps with associations between them. Also, the abstraction an ORM provides makes code more easy to read and usually allows to more easily port an app to a different database.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值