1

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

我试图在存储过程中包含输出参数并将其设置为 LAST_INSERT_ID()。仍然insertedId为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
4

2 回答 2

2

由于我只需要使用存储过程,因此我在插入存储过程中选择了添加的记录。这使得该记录在调用 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]);
      }
    }
  );
});
于 2019-06-11T19:57:31.223 回答
0
于 2019-06-11T11:58:23.697 回答