Take only one value in the query result to the database

Asked

Viewed 322 times

0

I’d like him to pass one return with only the number of data of that table, however it is returning it:

C:\E. S>node dao.js
Connected!
[ RowDataPacket { 'COUNT(*)': 4 } ]

Code:

contaQuantidade(tabela){
        var conector = this.conectaBanco();
        conector.connect(function(err) {
            if (err) throw err;
            console.log("Connected!");          
            conector.query("select COUNT(*) from "+tabela, function (err, result) {
                if (err) throw err;
                var i = result;
            });
            conector.end();
        });
        return i;
    }

How do I pick only the number 4?

1 answer

1

You can use the AS to create an alias for COUNT(*), to make it easier to access in Javascript. So your query will look like this:

SELECT COUNT(*) AS count FROM nome_da_tabela;

The result will come like this:

+-------+
| count |
+-------+
|     4 |
+-------+

Then, to access the value, we need to access the first item of RowDataPacket returned. For this, we will use the following notation:

// Acessa o primeiro elemento dos resultados:
//    ↓↓↓
result[0]

And to access the number returned, just access the property count, as we define as alias in our query.

result[0].count

The code goes something like this:

connection.query('SELECT COUNT(*) AS count FROM ' + table + ';', (err, result) => {
  if (err) throw err

  // ℹ️ Acessamos o número de tabela na linha abaixo:
  const number = result[0].count

  console.log('Temos ' + number + ' registros na tabela ' + table + '.')
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.