Nodejs Mysql Limit

MySql Limit is used to get the number of records from the table as your requirements.
to create the MySQL select query with a Limit clause in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Suppose, You want to get the user details based on limit 1.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users limit 1', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 1, name: ‘John’, age: 35 } ]