【问题标题】:How to get the insrted row data in nodejs-mysql insert query?如何在节点js-mysql插入查询中获取插入的行数据?
【发布时间】:2019-07-27 18:32:22
【问题描述】:

我有一个简单的插入查询,如下所示:

let sql = "INSERT into users(name, date) VALUES ('"+name+"', '"+date+"')";
  connection.query(sql, (err, result) => {
      if(err) {
          res.status(500);
      } else {
        res.send(result) // we have here an object that has only the inserted id  
      }
  });

我真正想要的是获取插入的行数据而不仅仅是 id 而无需进行另一个选择查询来获取它们。

有没有办法在一个查询中实现这一点?

【问题讨论】:

标签: mysql node.js insert


【解决方案1】:

如果您正在使用:

// include mysql module var mysql = require('mysql');

mysql 模块不会返回插入查询的数据。它正在返回:

  • Number of rows affected, Number of records affected with the warning, Message

如果您想获取插入的数据,您应该使用查询构建器或 ORM,如 Sequelize。 enter link description here

【讨论】:

    【解决方案2】:

    您可以使用它来检索

    let sql = "INSERT into users(name, date) VALUES ('"+name+"', '"+date+"') ; SELECT * FROM users WHERE id = SCOPE_IDENTITY()";
      connection.query(sql, (err, result) => {
          if(err) {
              res.status(500);
          } else {
            res.send(result) // we have here an object that has only the inserted id  
          }
      });
    

    SCOPE_IDENTITY()返回最后插入的标识值

    【讨论】:

      【解决方案3】:

      您可以使用以下代码获取最后插入的 id:

      SQLconnnection.query(sql, (err, result) => {
            if(err) {
                console.error(err);
            } else {
               console.log(result) ;
               /*Output=>{affectedRows: 1
                          changedRows: 0
                          fieldCount: 0
                          insertId: 1 =>Last inserted ID Here
                          message: ""
                          protocol41: true
                          serverStatus: 2
                          warningCount: 0}*/
             console.log(result.insertId);//=>last inserted id get
            }
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-20
        • 1970-01-01
        • 2019-12-23
        • 2018-08-07
        • 2018-03-19
        • 2014-08-17
        • 2021-07-02
        相关资源
        最近更新 更多