Update data with NodeJs [duplicate]

こ雲淡風輕ζ 提交于 2020-03-04 17:52:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!