简体   繁体   中英

Update query using MySQL and Node.js

I am using Node.js with MySQL. Everything works fine, however I am having issues when using the UPDATE query.

My database table looks like this:

id     | employeeId
54027  | 8241
63708  | 3421
393835 | 3687

To check for external updates, I am sending a request to an API using the following code:

const obj = response.data.map(function(item) {
        return { id: item.entryId.id, employeeId: item.employeeId.id };
});

A console.log of this, returns the following:

[ { id: 54027, employeeId: 8242 },
  { id: 63708, employeeId: 3422 },
  { id: 393835, employeeId: 3688 }
]

So, since my API call has returned data which is different than what is in my DB, I want to issue an UPDATE query to MySQL, using the following code:

const query = connection.query('UPDATE entries SET employeeID = ? WHERE entrieId = ?', obj,
(error, results, fields) => {
    if (error) console.log(error);
    else {
        console.log('Updated!');
    }
});

I get an error saying that I am using the wrong SQL syntax, then I get this at the bottom:

UPDATE entries SET employeeID = id = 54027, employeeId = 8242 WHERE entrieId = id = 63708, employeeId = 3422

I have been following tutorials and other advice found on forums / documentation for the best and correct way to issue the UPDATE, and am getting confused by my result.

let query = '';
for(var i = 0, len = obj.length; i < len; i++) {
query += 'UPDATE entries SET employeeID ='+obj[i]['employeeID']+' WHERE entrieId = '+obj[i]['id']+';'
}
 connection.query(query,
(error, results, fields) => {
    if (error) console.log(error);
    else {
        console.log('Updated!');
    }
});

When formatting SQL queries, JSON objects are turned into key = 'val' pairs. Have a look at https://github.com/mysqljs/sqlstring#escaping-query-values . Consider the following code,

var data = {email: "e@example.com", status: 2} // consider some dummy data
var formattedQ = SqlString.format("UPDATE users SET ? WHERE id = 34", data);

// formattedQ would be:
"UPDATE users SET `email` = 'e@example.com', `status` = 2 WHERE id = 34"

For your problem you should use an array of values containing employeeId and id .

var data = [8242, 54027] // 8242 is employeeId and 54027 is id.
var q = "UPDATE entries SET employeeID = ? WHERE entrieId = ?";
connection.query(q, data, (err, results, fields) => {
    // Your code here
});

// This would execute the following formatted query:
UPDATE entries SET employeeID = 8242 WHERE entrieId = 54027

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM