How to connect mysql database in node js with example?

How to connect mysql database in node js with example?

In this post we will give you information about How to connect mysql database in node js with example?. Hear we will give you detail about How to connect mysql database in node js with example?And how to use it also give you demo for it if it is necessary.

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:

server.js

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:

Also see:Laravel 5 – Authenticate user in NodeJS with socket io using JWT.

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…

Hope this code and post will helped you for implement How to connect mysql database in node js with example?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

1  +  6  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US