在节点js中传递mysql查询回调函数的额外参数

时间:2017-01-12 09:46:43

标签: node.js

我正在尝试使用节点js运行mysql查询,并且在回调函数中我想传递一些额外的参数。

for (var i = 0; i < categories.length; i++)
{
    connection.query ('select * from products where category=' + categories[i] , function (err, products) {
            if (products != undefined && products.length > 0) 
            {
                // want to do some processing based on product data and category name   
            }
    });
}

在上面的代码中,如何将类别名称传递给回调函数?我知道我可以在sql查询中加入,这将为我提供产品中的数据,但只是想知道是否还有回调函数中的数据传递。

1 个答案:

答案 0 :(得分:0)

只需使用const即可。此外,永远不要通过简单地将字符串与变量连接来构造查询。

示例:

for (var i = 0; i < categories.length; i++)
{
    const categoryName = categories[i];
    connection.query('select * from products where category = ?',
                     [categoryName],
                     function (err, products) {
      if (err)
        throw err;
      if (products.length > 0)
      {
        // use `categoryName`
      }
    });
}

您可能还想考虑使用数据库连接池而不是单个连接(因为所有查询都排队,并且每个连接在任何给定时间只能执行一个查询)。