1

I want to update database in for loop with mysql query.

 for(let i=0;i<userarray.length;i++){
console.log(i);
     var sql = "update user set user_status=1 where id=" + userarray[i].id;
    con.query(sql, function(err, result) {
                    if (err) throw err;     
 console.log("Number of row update: " + result.affectedRows);


                });
     }
and the output is:
1
2
3
4
Number of row update:1
Number of row update:0
Number of row update:0
Number of row update:0

Here only one time database is updating.I found async/await is solution but i dont know how to use it.

3
  • Looping through each user id and executing one query per user id is highly ineffidient. Construct a single query instead and execute that single query one time. Something like update user set user_status=1 where id in (userarray[0], userarray[1]...) Commented Oct 10, 2018 at 5:05
  • Which library are you using for the database connection ? Commented Oct 10, 2018 at 6:29
  • mysql library .. Commented Oct 10, 2018 at 7:49

2 Answers 2

2

If you are using mysql library you should use the parameter to insert the ids

const userarray = [{id:0}, {id:2}, {id:5}];
const idsList = [userarray .map(user => user.id)];
const sql = "UPDATE user SET user_status = 1 WHERE id IN (?)";

con.query(sql, idsList, (err, result) => {
  if(err) throw err; 
  console.log(result);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you can use the IN operator within the SQL query

let sql = 'update user set user_status = 1 where id IN (';
const userarray = [
  {
    id: 1,
  },
  {
    id: 2,
  },
  {
    id: 3,
  },
];
for(let i = 0; i < userarray.length; i++) {
  const split = i === 0 ? '' : ',';
  sql += `${split}${userarray[i].id}`;
}
sql += ')';
console.log(sql)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.