在使用node.js的sql server数据库中,在不使用for循环的情况下一次插入多条记录时遇到问题



大家好,我是在nodejs中使用mysql库的新手,我对在数据库中同时插入多行的可能性感兴趣。我制作了一个简单的代码,它从数据库表中捕获用户注册id,并使用该用户选择的角色的索引。现在,我想将用户和角色id添加到role_user表中,该表分别具有user_id和role_id。

假设我想在不使用循环的情况下做3次:

Insert Into User_role VALUES (1,20);
Insert Into User_role VALUES (2,20);
Insert Into User_role VALUES (3,20);

,其中第一列的数字1,2,3是角色索引。

Error I'm getting is RequestError: Incorrect syntax near '?'.

如何使此查询工作?

if(req.body.roles){
var sqlQuery = `SELECT ID from Test_user Where email = @email`;
var indexiRola = findPositions(db.ROLES, req.body.roles);
request.input('role', db.sql.NChar, req.body.roles);
request.query(sqlQuery).then(
id => {
let ids = Array(req.body.roles.length).fill(id.recordset[0].ID);
console.log(ids); // [20, 20, 20]
let roleUsers = createSeperateLists(indexiRola, ids);
console.log(roleUsers); // [ [ 1, 20], [ 2, 20], [ 3, 20] ]
var insertQuery = `INSERT INTO Role_User ("role_ID", "user_id") VALUES ?`;
request.query(insertQuery, [roleUsers], function(err, result){
if(err) throw err;
console.log("Successfull insertion");
});
})
}

请检查是否有帮助。当然,我无法检查它是否在运行。

恰恰相反,它并不完整!request.query是异步的,必须修改该代码。

至少,正如我所希望的,这个代码不会进入RequestError: Incorrect syntax near '?'.

请:

  • 检查修订是否适用于一个输入
  • 每当您获得完整的解决方案时,请与我们分享
if (req.body.roles) {
var sqlQuery = `SELECT ID from Test_user Where email = @email`;
var indexiRola = findPositions(db.ROLES, req.body.roles);
request.input('role', db.sql.NChar, req.body.roles);
request.query(sqlQuery).then(
id => {
let ids = Array(req.body.roles.length).fill(id.recordset[0].ID);
console.log(ids); // [20, 20, 20]
let roleUsers = createSeperateLists(indexiRola, ids);
console.log(roleUsers); // [ [ 1, 20], [ 2, 20], [ 3, 20] ]
// I removed the double quotes from the names and,
// VALUES (?, ?) - this is the right syntax for SQL
const insertQuery = 'INSERT INTO Role_User (role_ID, user_id) VALUES (?, ?)';
// Then, forEach roleUsers
// By the way, [roleUsers] yields an array of arrays of arrays, not cool
roleUsers.forEach(
roleUser => {
request.query(
insertQuery,
roleUser,
// Oh! Shoot!!! This is async.
// Man, you will have to deal with it.
// Please, share with us the final solution!
function(err, result) {
if (err) throw err;
console.log("Successfull insertion");
}
);
}
);
})
}

最新更新