Node.js MySQL Acess


The node.js applications supported various types of database. MySQL is very important among them which fully support by node.js.



What is MySQL Database ??


To use the MySQL database we should use the MySQL driver called Connector/Node.js is the official Node.js driver for MySQL and we can download it from the NPM.

 

The MySQL setup download link available on the its official website www.mysql.com/download where the user can download and use in applications. 




Node.js connecting to MySQL database


Here we are going to explain how to create the MySQL database connection from the node js application.


 

Installing node.js driver for MySQL

 

First create the folder to store the node.js application and use the command npm-init to create the packeg.json file

 

Node init

Install node.js connector for the MySQL database use command as shown below


npm install mysql

We are creating the database called "northwind" for the demonstration purpose by using the command as shown below


CREATE DATABASE northwind;

Once the database created successfully than we can establish the connection by the node.js application. First import the MySQL module in node.js by using command as shown below


var mysql = require('mysql');

Now, Create the function createConnection() to create the connection with MySQL by passing necessary parameters like Host/Server, User, Password and database as shown below



var mysql = require('mysql');
var
connection = mysql.createConnection({
host: "localhost",
user: "username",
password: "password",
database: "northwind"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connection successfully established!");
});

Congratulation! After this tutorial, you have learned how to establish the connection to the MySql in the node.js application