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/

相关文章:

javascript - 访问部分 javascript 数组 (mysqljs)

node.js - Mocha 中跳过的测试在报告中显示为待处理

node.js - Aws ec2 实例在使用 docker 和 gitlab ci cd 时不断崩溃

javascript - 如何在 NodeJs 或 javascript 中的当前 unix 时间戳中添加 24 小时?

Node.js 和 MongoDB Atlas Mongoose 连接错误

node.js - 验证所有表单条目的中间件 express js, node js

javascript - 点击 6 次后 ui 路由器刷新崩溃

node.js - 错误请求 - Node js ajax 发布

mysql - 如何通过nodejs导入大量数据到mysql?