How to connect MySQL database in NodeJS with example?

How to connect MySQL database in NodeJS with example?

How to connect MySQL database in NodeJS with example?

Node.js is very popular in Todays for make chat system, real-time notification, real-time developing etc.

So, Today, I am going to give you very simple example of How to use MySQL Query in Node JS. If you use node.js then you can see how it is work and there are several driver for different task like redis, socket io, express etc.

But Node.js have a driver for MySQL that way we can easily connect with database and you can use select, insert, update and delete sql query.

So, in this example i going to give from scratch so if you are beginner and you haven't installed nodejs on your server then fire bellow command:

sudo apt-get update
sudo apt-get install nodejs

Ok, now we have to also need to install npm because we will install mysql package using npm command, so if you not installed this command before then install by following command.

sudo apt-get install npm

Ok, now we are ready for install mysql node.js driver by following command:

sudo npm install mysql

Now, I am going to give you very basic example, so first you have a one database "test" and inside that database you have "users" table.

Ok, so create new file server.js and put bellow code inside that file:

var mysql      = require('mysql'); 
var connection = mysql.createConnection({ 
  host     : 'localhost', 
  user     : 'root', 
  password : 'root', 
  database : 'test' 
});
connection.connect(); 
connection.query('SELECT * FROM users', function(err, result, fields) { 
  if (err) throw err; 
  console.log(result); 
}); 
connection.end();  

Now you have to run this file by following command:

nodejs server

Thanks

Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.

News & Blogs

2cda7519f703462a0eabd1c2e84e0001.jpg

Why shouldn’t you wait to jump onto Angular 2?

AngularJs is a JavaScript framework and is widely adopted framework in building Single Page Web A...

8b77d9abe1f73f94ea9f0f008ff988a1.jpeg

Difference between Sets vs. Arrays in JavaScript

The Set object type was introduced in the 2015 ECMAScript specification and is ready to be used i...

7ebe8f7d2be8625f6df997b5d45a86af.jpeg

How to Implement Real Time Notification Using S...

Real time web/versatile application are getting to be well known step by step. Administrations li...