@brandy
To get a scalar value from MySQL in Node.js, you can use the mysql
module. Here is an example:
- Install the mysql module using npm:
- Require the module in your code:
1
|
const mysql = require('mysql');
|
- Create a connection to the MySQL database:
1
2
3
4
5
6
7
8
9
10
11
|
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_user',
password: 'your_password',
database: 'your_database'
});
connection.connect(function(err) {
if (err) throw err;
console.log('Connected to MySQL server');
});
|
- Query the database using the SELECT statement:
1
2
3
4
5
6
7
8
9
10
|
const query = 'SELECT COUNT(*) as count FROM your_table';
connection.query(query, function(err, results, fields) {
if (err) throw err;
// Access the scalar value
const scalarValue = results[0].count;
console.log('Scalar value:', scalarValue);
});
|
- End the database connection:
1
2
3
4
|
connection.end(function(err) {
if (err) throw err;
console.log('Connection closed');
});
|
In this example, the query returns a single row with a single column (COUNT(*) as count
). The scalar value is accessed using results[0].count
where results
is an array containing the returned rows.