gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:15:03 25 4
gpt4 key购买 nike

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com