MySql 存储过程在 Node 中不起作用。

huangapple go评论71阅读模式
英文:

MySql stored procedure in Node not working

问题

我正在使用Node JS、Express和Mysql。我创建了存储过程,并在Mysql中调用存储过程会返回正确的结果,但在Node中调用时返回未定义的值。

我的存储过程:

DELIMITER //

CREATE PROCEDURE Read_Categories_SP()
BEGIN
	SELECT CategoryID, CategoryName
	FROM Categories
	ORDER BY CategoryName;
END //

DELIMITER ;

在MySQL Workbench中运行此存储过程会给我以下结果:

2 ARIA
1 IT
3 Workshop

在Node中:

    // 这不起作用
    const [result1] = await mysqldb.pool.query('CALL Read_Categories_SP');
    
    // 这个起作用
    const [result2] = await mysqldb.pool.query('SELECT * FROM Categories');

我在这里做错了什么?

英文:

I am using Node JS, Express and Mysql. I created stored procedures and calling the stored procedure from within Mysql yields the correct results, but calling it from Node yields undefined values.

My stored procedure:

DELIMITER //

CREATE PROCEDURE Read_Categories_SP()
BEGIN
	SELECT CategoryID, CategoryName
	FROM Categories
	ORDER BY CategoryName;
END //

DELIMITER ;

Within MySql Workbench running this procedure gives me:

2 ARIA
1 IT
3 Workshop

In Node:

    // This does not work
    const [result1] = await mysqldb.pool.query('CALL Read_Categories_SP');
    
    // This works
    const [result2] = await mysqldb.pool.query('SELECT * FROM Categories');

What am I doing wrong here?

答案1

得分: 0

这不是NodeJS的问题。您不需要这样调用它:

const result1 = await mysqldb.pool.query('CALL Read_Categories_SP');

这样应该可以工作。您将能够使用result1[0],...访问类别。

此外,要有适当的try-catch机制来处理错误。

编辑:似乎需要做一点小调整来访问MySQL查询的结果 -

const [rows] = await mysqldb.pool.query('CALL Read_Categories_SP()');
const result1 = rows[0];

通过将rows[0]分配给result1,您将能够进一步处理结果集的第一行。

英文:

This is not a problem with NodeJS. You don't need to call it like:

const [result1] = await mysqldb.pool.query('CALL Read_Categories_SP');

Change it to:

const result1 = await mysqldb.pool.query('CALL Read_Categories_SP');

That should work. You will be able to access the categories using result1[0], ...

And also, have a proper try-catch mechanism to handle errors.

Edit: It seems a small adjustment is needed to access the result of MySQL query -

const [rows] = await mysqldb.pool.query('CALL Read_Categories_SP()');
const result1 = rows[0];

By assigning rows[0] to result1, you will have the first row of the result set available for further processing.

huangapple
  • 本文由 发表于 2023年6月5日 13:18:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403642.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定