node.js-MySQL COUNT 记录数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11412599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:06:55  来源:igfitidea点击:

node.js-MySQL COUNT the number of records

mysqlnode.jsnode-mysql

提问by Shekhar

I have following code.

我有以下代码。

var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'test'
});
connection.connect();

var userdata = '24';

var sql = 'SELECT COUNT(*) FROM names WHERE age = ?'
connection.query(sql, [userdata], function(err, rows, fields) {
  if (err) throw err;
  console.log('Query result: ', rows);
});

connection.end();

I want to get the total number of records from table 'names' where 'age' = 24. I receive the following on my node.js command prompt.

我想从表 'names' 中获取记录总数,其中 'age' = 24。我在 node.js 命令提示符下收到以下内容。

Query result:  [ { 'COUNT(*)': '14' } ]

My question is how to store this number 14 in a variable for further use.

我的问题是如何将这个数字 14 存储在一个变量中以供进一步使用。

I know I can do this just by changing the 'sql' line to

我知道我可以通过将“sql”行更改为

var sql = 'SELECT * FROM names WHERE age = ?'

and then console line to

然后控制台行到

console.log('Query result: ', rows.length);

But still is there another way?

但是还有别的办法吗?

回答by Nemanja

Rewrite the

重写

var sql = 'SELECT COUNT(*) FROM names WHERE age = ?'

To look like, i.e.:

看起来像,即:

var sql = 'SELECT COUNT(*) AS namesCount FROM names WHERE age = ?'

Then, you will get Query result: [ { 'namesCount': '14' } ].

然后,您将获得查询结果: [ { 'namesCount': '14' } ].

so now you have

所以现在你有

rows[0].namesCount

Good enough?

够好了?