How to Connect MySQL Database in Node JS?

By Hardik Savani November 5, 2023 Category : MySql Node JS

Hey Guys,

I am going to explain to you example of nodejs mysql example. you can understand a concept of node.js mysql select query example. you can see node.js mysql sample code. This article will give you a simple example of mysql node js tutorial.

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.query('SELECT * FROM users', function(err, result, fields)


if (err) throw err;




Now you have to run this file by following command:

nodejs server

It is a very simple example, But If you want to get more information about node.js and mysql then follow link : Click Here.

Maybe It can help you...

Tags :