问题
I am trying to update my user data in database with node app (using expressJs) but it returns this error in terminal:
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL WHERE `id` = '1'' at line 1",
sqlState: '42000',
index: 0,
sql: "UPDATE `users` SET NULL WHERE `id` = '1'"
Code
index.js
var Users = require('./routes/Users');
app.put('/users/:id/update', Users.update);
Users.js
'use strict';
var response = require('../res');
exports.update = function(req, res) {
req.getConnection(function(err, connection) {
connection.query('UPDATE `users` SET ? WHERE `id` = ?', [req.body, req.params.id], function(err, rows) {
if (err)
console.log("%s ", err);
response.success(rows, res);
});
});
};
sending request
Can you tell me what i did wrong?
回答1:
You can do it with the code below:
exports.update = function(req, res) {
console.log(req.body);
console.log(req.params);
req.getConnection(function(err, connection) {
connection.query('UPDATE `users` SET ? WHERE ?', [req.body, req.params], function(err, rows) {
if (err)
console.log("%s ", err);
response.success(rows, res);
});
});
};
I've been trying with the code above and it's working fine.
Make sure your req.body
is not empty and the field in your req.body
it's same with the field in your users
table.
If your req.body
is undefined or null, then you can add this middleware to your express server:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
I hope it can help you.
回答2:
Looks like your sql
query has a problem. Please add a column name for update.
sql = `UPDATE users SET column = NULL WHERE id = '1'`
Or You can use
sql = `UPDATE users SET column = ? WHERE id = ?`
con.query(sql,[id]);
Before that Make create the connection.
NOTE: DON'T USE ''
for table name and column name
来源:https://stackoverflow.com/questions/59959755/update-data-with-nodejs