gpt4 book ai didi

node.js - 使用 nodejs 和 node-mysql 返回行

转载 作者:搜寻专家 更新时间:2023-10-31 22:36:48 27 4
gpt4 key购买 nike

我正在探索 Nodejs 和 node-mysql 模块。我有一个小问题。我找到的每个教程都解释了如何在数据库上进行选择,但它们从不返回行,它们总是记录它们,这对我的情况来说绝对没用。

我有一个 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 而不是 ORM(sequelize、persistence.js ...)的优缺点

谢谢

最佳答案

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,那真的取决于用例。我会选择一个 ORM(我最喜欢 MySQL 的是 patio ),以防我的应用程序需要多个(复杂的)模型,也许它们之间存在关联。此外,ORM 提供的抽象使代码更易于阅读,并且通常允许更轻松地将应用程序移植到不同的数据库。

关于node.js - 使用 nodejs 和 node-mysql 返回行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16264162/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com