Home mysql How to connect mysql database in node js with ?

How to connect mysql database in node js with ?

by Shahriar Sagor
connect mysql database in node js

Today now in this post i want to show you How to connect mysql database in node js with ? Now Node.js is a very popular for making the chat system, or real-time notification, real-time developing etc.

Here I am going to give you a very simple example about How we can use MySQL Query in our Node JS. If you are know about node.js then you must see here how it is work and there are the several driver for the different task as like redis, socket io, express etc.

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

So, now in this example i am going to give this example from the scratch. If you are a beginner and also you haven’t installed the nodejs on our server then need to fire bellow command:

sudo apt-get updatesudo apt-get install nodejs

Now you have to also need install the npm because here we will install mysql package by using npm command. So if you not installed this before then you can install by following command.

sudo apt-get install npm

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

sudo npm install mysql

Now, here I am going to give you a very basic example. So first you have need a one database as “test” and inside that database you need a “users” table.

Ok, now create a new file as name server.js and put the 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 need to run this project by using following command:

nodejs server

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook


You may also like