我正在发现Nodejs和node-mysql模块。我有个小问题。我找到的每个教程都解释了如何在数据库上执行select,但它们从不返回行,它们总是记录这些行,这对我的情况完全没有用处。
我有一个app.js文件:
// Get continents
app.get("/continents", function(request, result) {
console.log("Continents : " + database.findAllContinents());
});和一个mysql.js文件:
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);
};如何让函数返回行,以便在app.js文件中使用它们?我并不是真的想在app.js文件中创建连接,我想分离DAO层。你有什么想法吗?
此外,如果有人知道使用node-mysql而不是对象关系数据库(sequelize,persistence.js...)的优缺点。
谢谢
发布于 2013-04-28 23:12:54
query()是一个不能返回任何结果的异步函数。因此,任何调用异步函数本身的函数(比如您的findAllContinents)也不能。
相反,您需要传递一个回调函数(也解释为here),该函数将在查询完成时调用:
// 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);
});
};至于(不)使用ORM,这实际上取决于用例。我会选择一个对象关系模型(我最喜欢的MySQL是patio),以防我的应用程序需要多个(复杂的)模型,可能它们之间有关联。此外,ORM提供的抽象使得代码更容易阅读,并且通常允许更容易地将应用程序移植到不同的数据库。
发布于 2021-06-10 18:55:03
此代码用于检查数据库中是否有任何单行
if(result.length == 1) {
var row = result[0];
console.log(row);
}https://stackoverflow.com/questions/16264162
复制相似问题