从nodejs调用存储过程返回错误

wlzqhblo  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(397)

我正在用expressjs研究nodejs,到目前为止还不错,但我有一个小问题:从workbench调用存储过程一切都正常,但是express中的同一句话(copy/paste)显示mysql引擎出错。

{
    "desc_status": {
        "code": "ER_BAD_NULL_ERROR",
        "errno": 1048,
        "sqlMessage": "Column 'id_color' cannot be null",
        "sqlState": "23000",
        "index": 0,
        "sql": "CALL pinturas.add_inventory('101', '3');"
    },
    "code_status": 409
}

这是我的点名:

let sql = "CALL pinturas.add_inventory(101, 3);";
conn.query(sql, true, (err, filas) => {
    if(err){
        //next(err);
        res.status(409).json({
            desc_status: err,
            code_status: 409,
        });
        return;
    }
    (...)
});

从工作台调用

CALL `pinturas`.`add_inventory`('101', '3');

最后,存储过程:

CREATE DEFINER=`root`@`localhost` PROCEDURE `add_inventory`(
    IN _id_color INT(11), 
    IN _cant INT(11)
)
BEGIN
    set @numRows = (select count(*) from stock_colores where id_pintura = 1 and id_color = @_id_color);
    if @numRows > 0 then
        set @oldCant = (select cant from stock_colores where id_pintura = 1 and id_color = @_id_color);
        set @_stock_id = (select stock_id from stock_colores where id_pintura = 1 and id_color = @_id_color);
        update stock_colores set cant = (_cant + @oldCant) where stock_id = @_stock_id;
    else
        insert into stock_colores (id_pintura, id_color, cant) values (1, @_id_color, _cant);
    end if;
END

我很感激你的指导。干杯。

r1zhe5dt

r1zhe5dt1#

所以伙计们,经过几次检查和尝试,我成功地解决了我的问题,这实际上非常简单,而且全部都在我的存储过程脚本中。我是用@调用参数的,但实际上这些参数是在代码中声明的变量,而不是输入参数。
这是我的最新代码。

CREATE DEFINER=`root`@`localhost` PROCEDURE `add_inventory`(
    IN _id_pintura INT(2), 
    IN _id_color INT(2), 
    IN _cant INT(2)
)
BEGIN
    set @numRows = (select count(*) from stock_colores where id_pintura = _id_pintura and id_color = _id_color);
    if @numRows > 0 then
        set @oldCant = (select cant from stock_colores where id_pintura = _id_pintura and id_color = _id_color);
        set @_stock_id = (select stock_id from stock_colores where id_pintura = _id_pintura and id_color = _id_color);
        update stock_colores set cant = (_cant + @oldCant) where stock_id = @_stock_id;
    else
        insert into stock_colores (id_pintura, id_color, cant) values (_id_pintura, _id_color, _cant);
    end if;
END

相关问题