Node.js-MySQL COUNT number of records

I have the 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 the table names' where 'age' = 24. I get the following at the node.js command line.

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

My question is how to store this number 14 in a variable for future reference.

I know I can do this by simply changing the string 'sql' to

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

and then the console on

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

But is there still another way?

+7
source share
1 answer

Rewrite

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

To look like this, for example:

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

Then you will get the result of the query: [ { 'namesCount': '14' } ].

So now you have

 rows[0].namesCount 

Good enough?

+25
source

All Articles