Mysql Connection in node js

Node.js has in-built modules to support connection with MySQL Database. For making node.js connection with MySQL, first install MySQL on your machine and after that install the mysql npm module.

Install mysql using npm.

For this go to command prompt and enter this code -

npm install mysql

Nodejs mysql connection

To connect to mysql server, we will create a connection with mysql module. So, first include the mysql module, then call the create connection method. Make sure to enter the right hostname, username, password and database of your mysql server.

Here is the sample code to connect to database.

var mysql = require("mysql");
var con = mysql.createConnection({
    host: "hostname",
    user: "username",
    password: "password",
    database: "database"
    if(err) {
        console.log('Error connecting to Db');
    console.log('Connection Established');
con.end(function(err) { 

The createConnection is predefined method used with mysql module to create a connection with mysql.