To connect with MySQL, Firstly we have to install MySQL module in the Nodejs
npm i mysql --save
now create 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;
// Now create server.js file
now include the connection.js file
const pool = require('./connection');
pool.getConnection(function(err, connection) {
if (err) {
console.error('error in db connection');
return;
}
console.log('db is connected');
return ;
});
Now run the server.js file
node server.js
Note:- if you add correct database credentials the show “db is connected” otherwise not.