Nodejs connect with Mysql

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.

select query

pool.query('SELECT * FROM users', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

insert query

pool.query('insert into users(name,age) values(:Name,:Age)',{Name:'John',Age:35}, function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

update query

var post  = {name: 'Rom', age:30};
pool.query('update users SET name=:Name,age=:Age where id=:Id',{Name:'Rom',Age:30,'Id':1}, function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

delete query

var post  = {name: 'Rom', age:30};
pool.query('delete from users where id=:Id',{Id:1}, function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});