Sunday, April 26, 2020

Setting Node.js MySQL Connection

Setting Node.js MySQL Connection

node mysql


We can create applications with databases using Node.js. In this tutorial, we will create a node application connected with the MySQL database. MySQL is a very popular RDBMS. To create this application we need to,

  1. Install MySQL
  2. Install MySQL driver
  3. Create a connection
  4. Execute and test

Install MySQL


To install the MySQL database, we first need to download the database from https://www.mysql.com/downloads/ and then install it to your machine,

Install MySQL driver


Once MySQL database is up and running, then we need to install MySQL driver by using npm. We need to “mysql” module in our application to access the database. This driver will provide a layer to access the database programmatically.

To download and install the "mysql" module, open the Node.js Command Terminal and run the following command(npm install mysql),

C:\Users\me>npm install mysql

Upon the successful completion of the installation, you will be able to see something like 

nodejs mysql

Now, we can access and manipulate the database with this database driver. This module can be used as,

var mysql = require('mysql');

Create a Connection


Create a .js file and place the code in this file (Let the name of the file be con.js)

    var mysql = require('mysql');

    var con = mysql.createConnection({
      host: "localhost",
      user: "username",// replace with username
      password: "password" // replace with password 
    });

    con.connect(function(err) {
      if (err) throw err;
      console.log("Connected!");

    });

Execute and test


The result will be

 C:\Users\me\Desktop\brackets>node con.js
Connected!


Now, Node.js is connected to the MySQL database.