Sunday, 13 November 2016

Connect your mysql database with node.js

Node.js is popular framework today and real time things is possible with the node.js like real-time chat notification etc.So today i am going to show you how to connect node.js with mysql database.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.

Mysql Node.js

So lets start :

Step 1: Installed node.js if it is not installed in your system. 

sudo apt-get update
sudo apt-get install nodejs

You can read this post for installing the node.js from scratch

Step 2: Install npm for package management support.

sudo apt-get install npm

Now install the mysql package for node.js

sudo npm install mysql

I'm supposing you have installed php , mysql in your system and we are using node(database) if you don't have a database with name node then create it and inside it a users table .

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

Step 3 : Ceate a new file.

var mysql      = require('mysql'); 

var connection = mysql.createConnection({ 
  host     : 'localhost', 
  user     : 'root', 
  password : 'root', 
  database : 'node' 


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

This is very basic for mysql using node. you can explore node with the mysql here:

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts