【发布时间】:2018-04-17 11:08:36
【问题描述】:
我遇到了需要在我的 Node 项目中使用批量插入的情况。
这当然已经在这里回答了:How do I do a bulk insert in mySQL using node.js
但是,我有一个用于创建 api 的 express 项目。参数变成了一个数组,我在使用该数组进行批量插入时遇到了问题。每当我尝试使用该路由时,都会收到 Error: ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value count at row 1 的错误消息
经过一番挖掘,我发现它试图插入:
['foo', 'bar', 'test']
当我需要插入时:
['foo']
['bar']
['test']
不管怎样,这是完整的代码:
路线
router.post("/", function (req, res, next) {
db.query(
"REPLACE INTO user (`Name`) VALUES (?)",
[req.query.array],
function (error, response) {
if (error) throw error;
console.log(response);
}
)
});
路由调用者
let requestUrl = "http://localhost:3000/user?";
// External api request which returns a list of users
for (let i = 0; i < body.users.length; i++) {
requestUrl += `array=${body.users[i]}&`
}
let addUserRequest = {
url: requestUrl,
method: "POST"
};
request(addUserRequest, function (error, response, body) {
console.log(body);
});
生成的url是:
http://localhost:3000/user?array=foo&array=bar&array=test
【问题讨论】: