27

I trying to update some info in MYSQL DB, but I'm not sure of how to do it with in node.js. This is the mysql driver I'm using https://github.com/felixge/node-mysql

What I have so far

connection.query('SELECT * FROM users WHERE UserID = ?', [userId], function(err, results) {
if (results[0]) {
if (results[0].Name!=name) {
console.log(results[0].Name);
connection.query('UPDATE users SET ? WHERE UserID = ?', [userId], {Name: name});
}
console.log(results[0].UserID);
}
});

Everything works except...

connection.query('UPDATE users SET ? WHERE UserID = ?', [userId], {Name: name});

In PHP I would have this...

mysql_query("UPDATE users SET Name='".$_GET["name"]."' WHERE UserID='".$row['UserID']."'");

I'm not sure what I'm doing wrong, But I'm positive that the issue is here

connection.query('UPDATE users SET ? WHERE UserID = ?', [userId], {Name: name});
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
agdurrette
  • 373
  • 1
  • 3
  • 5

6 Answers6

52

The answer by ruakh isn't entirely correct, you can use the SET ? feature with another ?.

The syntax is:

connection.query('UPDATE users SET ? WHERE UserID = ?', [{ Name: name }, userId])
Josh Laird
  • 6,974
  • 7
  • 38
  • 69
Bala Clark
  • 1,524
  • 12
  • 19
50

[Note (added 2016-04-29): This answer was accepted, but it turns out that there is a reasonable way to use SET ?. For details, see Bala Clark's answer on this same page. —ruakh]


From the code for Connection.prototype.query() and Connection.createQuery(), it's clear that you can only pass in a single values object. I don't see where the code for the special SET ? behavior is defined — it's clearly not in SqlString.formatQuery() — but if it uses SqlString.objectToValues(), then I guess there's no way to use it together with another ?.

I think the best approach is to just dispense with the neat SET ? feature, and write either of these:

connection.query('UPDATE users SET Name = ? WHERE UserID = ?', [name, userId])
connection.query('UPDATE users SET Name = :Name WHERE UserID = :UserID',
                     {UserID: userId, Name: name})

but if you really want to use SET ?, I suppose you could write this:

connection.query('UPDATE users SET ? WHERE UserID = :UserID',
                     {UserID: userId, Name: name})

which would update both UserID and Name; unless you have a trigger, this should be O.K., in that it's updating UserID to the value it already had anyway. But it's kind of disconcerting, and I don't recommend it.

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • @MarcioJasinski: Thanks for your edit suggestion, but it really changes this answer in a way that will invalidate other answers on this page. I'll see if I can find a more graceful way to add that information . . . – ruakh Apr 29 '16 at 16:57
  • 1
    You should mention that in order for your `:Name` and `:UserId` implementation to work one needs to include a [custom-format](https://github.com/mysqljs/mysql#custom-format) configuration. – DrDirk Jan 20 '18 at 19:06
22

You can use an array of objects:

connection.query('UPDATE user SET ? WHERE ?', [{ Name: name }, { UserId: userId }])
Marcel
  • 7,909
  • 5
  • 22
  • 25
0

This is what worked for me

 var records = 
 [name,email,adhar,ROLE,NOTES,REQUESTFORSUPPLIER,PASSWORD,LOCATION,CREATEDBY,CREATEDON,MODIFIEDBY,MODIFIEDON,mobile];

    var sql="UPDATE flavica_user SET Name=?,EMAIL=?,AADHAR=?,ROLE=?,NOTES=?,REQUESTFORSUPPLIER=?,PASSWORD=?,LOCATION=?,CREATEDBY=?,CREATEDON=?,MODIFIEDBY=?,MODIFIEDON=? WHERE USER_MOBILE=?"
    //var sql="UPDATE `flavica_user` SET ? WHERE ?";
    //this sql updates flavica_user
    con.query(sql,records,(err,result)=>{

      if(err){
        res.json({
          status:400,
          message:err
        })
      }

      else{
        res.json({
          status:200,
          message:result
        })
      }

    })
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
0

enter image description here

let query_1 =  `UPDATE reindexing_status SET success="Failure" where status="In Progress"`;
await updateValues(db_connection,query_1);
 
if(lambdaInvokeStatusCode === 200)

{
   let query_1 =  `UPDATE reindexing_status SET success="Success" where status="In Progress"`;
   await updateValues(db_connection,query_1);
   
   let query_2 =  `UPDATE reindexing_status SET end_time='${indexedAt}' where status="In Progress"`;
   await updateValues(db_connection,query_2);
   
   let query_3 =  `UPDATE reindexing_status SET status="Complete" where status="In Progress"`;
   await updateValues(db_connection,query_3);
   

}



async function updateValues(db_connection,sql) {
await new Promise((resolve, reject) => {
    db_connection.query(sql, function (err, result) {
        if (err) {
            console.log(err);
            reject(err);
        }
        else {
           
            console.log("RDS Updated Successfully",result );
            resolve("RDS URL Column: " + JSON.stringify(result));
        }
    });
 
});
}
Ajay
  • 176
  • 6
0

connection.query('UPDATE users SET Column_name = ? WHERE UserID = ?', [update_Value, userId]);