【问题标题】:How to make dynamic number of mysql queries in nodejs?如何在nodejs中进行动态数量的mysql查询?
【发布时间】:2020-04-14 18:11:57
【问题描述】:
我正在为如何从 NodeJS 向 MySQL 服务器发送几个 SQL 更新查询而苦苦挣扎。我需要某种同步执行。
情况:
- 我有一个对象数组。 (让我们说“formValues”)
- 其中一些对象可能在数据库表中有对应的行,而其他对象则没有。
- 我需要对数组中的每个对象执行 MySQL 查询,以了解需要在 MySQL 中为哪个对象创建新行以及只需要更新哪个对象。
- 最后我需要更新/创建 MySQL 表中的行。
- 我需要一种用于整个过程的回调。
这或多或少是一个关于如何使用 NodeJS 解决此类情况的一般性问题。据我了解,MySQL 查询是异步执行的。
如何实现,我可以循环遍历数组来构建需要更新的条目列表,另一个要在 MySQL 表中创建?
是否有任何“同步”MySQL 查询?
问候
詹斯
【问题讨论】:
标签:
mysql
node.js
asynchronous
【解决方案1】:
您可能真的从切换到 async/await MySQL 客户端中受益。您正在使用的客户端可能已经支持此功能。
但即使你没有,而且你不能切换它仍然是迄今为止最简单的编写一个帮助函数,将你的基于回调的 mysql 转换为基于 Promise 的。
有效的方法变成:
for(const formValue of formValues) {
await mysql.query('....');
}
在没有 async/await 和回调的情况下执行此操作要困难得多。
我想一种方法可能是这样的:
function doQueriesForFormValue(formValues, cb) {
const queries = [];
for(const formvalue of formValues) {
queries.push('...');
}
runQueries(queries, cb);
}
function runQueries(queries, cb) {
// Grab the first query
const currentQuery = queries[0];
mysql.query(currentQuery, (res, err) {
if (err) {
cb(null, err);
}
if (currentQueries.length>1) {
// Do the next query
runQueries(currentQueries.slice(1), cb);
} else {
// call final callback
cb(true);
}
});
}
我写了an article,其中包含一些在 Node.js 中使用 MySQL 的有效模式。或许有用