繁体   English   中英

通过 mysql npm package 更新错误

[英]Error in UPDATING thorugh mysql npm package

我正在尝试通过 mysql npm ZEFE90A8E604A7C840E88D03A687 更新 mysql 数据库。 我正在使用 express。我需要有关以下查询的帮助。

app.put("/api/movies/:id", (req, res) => {
  let id = parseInt(req.params.id);
  let values = [...Object.values(req.body)];
  values.push(id);
  let fields = 'SET Rank = ?, SET Title = ?, SET Description = ?, SET Runtime = ?,\
  SET Genre = ?, SET Rating = ?, SET Metascore = ?, SET Votes = ?,\
  SET Gross_Earning_in_Mil = ?, SET Director = ?, SET Actor = ?, SET Year = ?';

  connection.query("UPDATE moviesList " + fields + " \
  WHERE Id = ?", values , (err, rows) => {
    if(err) {res.send(err); console.log(err);}
    else res.send(rows.message);
  });
})

我能够插入表格,但在更新时出现上述代码的以下错误,

code: 'ER_PARSE_ERROR',
  errno: 1064,
  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 \'SET Title = \'Pulp Fiction\', SET Description = \'The lives of two mob hitmen, a bo\' at line 1',
  sqlState: '42000',
  index: 0,
  sql:
   'UPDATE moviesList SET Rank = 5, SET Title = \'Pulp Fiction\', 
SET Description = \'The lives of two mob hitmen, a boxer, a gangster\\\'s wife, and a pair of diner 
bandits intertwine in four tales of violence and redemption.\', 
SET Runtime = 154,   SET Genre = \'Crime, Comedy\', SET Rating = 8.9, SET Metascore = 94, SET Votes = 1511653,   SET Gross_Earning_in_Mil = 107.93, SET Director = \'Quentin Tarantino\', SET Actor = \'John Travolta\', SET Year = 1994   WHERE Id = 5' }

问题是 w.r.t 定义的字段。

您应该以以下格式定义

例如:

let fields = 'SET Rank =? , 标题 =?, 描述 =? , Runtime =?, Genre =?, Rating =? '

请参考此链接: https://www.technicalkeeda.com/nodejs-tutorials/nodejs-mysql-update-query-example

如果您仔细构建流程的每个步骤,该模块提供了很大的灵活性,可以节省您的时间。 只要键与您正在查询的表中相应字段的列名匹配,它将接受 object 进行INSERTUPDATE

因此,如果您能够定义通过req.body的键值,您可以让事情非常轻松地通过,而无需任何额外的操作或映射。

考虑以下更新后的代码示例,其中包含如何构建req.body上游的示例:

// example of what req.body would need to look like:
{
  "Rank": "value_a",
  "Title": "value_b",
  "Description": "value_c",
  "Runtime": "value_d",
  "Genre": "value_e",
  "Rating": "value_f",
  "Metascore": "value_g",
  "Votes": "value_h",
  "Gross_Earning_in_Mil": "value_i",
  "Director": "value_j",
  "Actor": "value_k",
  "Year": "value_l"
}

app.put("/api/movies/:id", (req, res) => {
  let id = req.params.id;
  let payload = req.body;

  connection.query("UPDATE moviesList SET ? WHERE Id = ?", [payload, id], (err, rows) => {
    if (err) throw err;
    console.log('changed ' + rows.changedRows + ' rows');
    // res.send(rows.message); 
      // in this context rows is the response object from the module
      // message is not a sub-object of the feature so rows.message
      // would likely fail
  });
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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