node.js - 使用 mysqljs 和存储过程发布后 insertId 返回 0

标签 node.js express mysqljs

使用 mysqljs 通过express.js 中 webAPI 端点的存储过程查询 mySQL 数据库。我需要返回插入的对象。为此,我尝试根据 mysqljs 的文档访问 insrtedId。但 insertid 总是返回零。

我尝试将输出参数包含在存储过程中并将其设置为 LAST_INSERT_ID()。还是insertId为0

router.post("/", (req, res) => {
  name = req.body.name;
  apiconnection.query(
    `CALL userAdd ('${name}', @_LID)`,
    (error, rows, fields) => {
      if (error) {
        res.json({ message: `cant be saved to the database` });
      } else {
        const id = rows.insertId;
        router.get("/", (req, res) => {
          apiconnection.query(
            `select * from tbl1 where id = ${id}`,
            (error, rows, fields) => {
              if (!error) {
                res.json(rows);
              } else {
                res.json(error);
              }
            }
          );
        });
       }
    }
  );
});

here is the stored procedure 

```CREATE DEFINER=`root`@`localhost` PROCEDURE `userAdd`(IN _name varchar(250), OUT _LID int)
BEGIN
  insert into tbl1(name) values (_name);
  set _LID = LAST_INSERT_ID();
END```

note that the id is set to auto increment

最佳答案

由于我只需要使用存储过程,因此我在插入存储过程中选择了添加的记录。这使得该记录在调用 POST 方法时可用。

CREATE DEFINER=`root`@`localhost` PROCEDURE `userAdd`(IN _name varchar(250), OUT _LID int)
BEGIN
  insert into tbl1(name) values (_name);
  set _LID = LAST_INSERT_ID();
  select * from tbl1 where id = _LID;
END

然后在 POST 方法中,添加的记录可以作为对象从行中访问 'rows[0][0]' 。无需对数据库进行 get 调用

   router.post("/", (req, res) => {
  name = req.body.name;
  apiconnection.query(
    `CALL userAdd ('${name}', @_LID)`,
    (error, rows, fields) => {
      if (error) {
        res.json({ message: `cant be saved to the database` });
      } else {
        res.json(rows[0][0]);
      }
    }
  );
});

关于node.js - 使用 mysqljs 和存储过程发布后 insertId 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56511731/

相关文章:

node.js - 在 Pug/Jade 中迭代未知的 JSON

node.js - 对于非本地、非生产环境的 NodeJS 项目,nwrl nx 环境文件不会被替换

node.js - 如何在ejs模板中使用in_array

node.js - Node Mysql 转义 - Mysql.Escape()/Mysql.EscapeId()

javascript - 如何调试通过 mysql2 发送的查询?

javascript - 可以使用 Node.js 中的传递/帮助函数调用异步生成器吗?

javascript - 类型错误 : object is not a function Node js Node Authentication

node.js - 在方法之间传递变量 Node.js Express.js

angularjs - 如何使用 Angular 获取登录用户?

node.js - 使用 MySQL 对 NodeJS Express API 进行 Web 打包会在模式 '-p' 而非 '-d' 中引发连接错误