Nodejs node-mysql查询结果数据types

我无法弄清楚如何从callback函数中的mysql查询中获取数据。 例如,我有如下查询:

mysqlConnection.query('SELECT COUNT(*) from card AS count', function (err, result) { if (err) { throw err; } else { console.log(Type.of(result)); console.log("card count is as: " + result.count); console.log("Card count is: " + result["COUNT(*)"]); console.log(result); } }); 

这打印出来:

 [Function: Array] card count is as: undefined Card count is: undefined [ { 'COUNT(*)': 3 } ] 

什么是“[Function:Array]”数据types,以及如何从中selectvariables? 一组函数? 为什么“result.count”未定义,即使我在查询中使用AS的东西。

下面的查询又如何与下面的查询不同呢?

 mysqlConnection.query('SELECT COUNT(*) from card AS count', function (err, rows, fields) { }); mysqlConnection.query('SELECT COUNT(*) from card AS count', function (err, result) { }); 

我什么时候使用另一个,当另一个?

使用function (err, rows, fields)的callback更适合于select正在使用的数据,然后行将由数组数组填充。 所以,在你的情况rows[0]['COUNT(*)']将是你的计数。

对于具有多行的select,您可以遍历结果。

作为一个方面说明,我认为你的意思是SELECT COUNT(*) AS count from card然后可以更简单地访问rows[0].count

改变你的查询

 SELECT COUNT(*) AS count from card 

select列后应该定义列别名,而不是在后面。