How to Connect to MySQL Database from a Web-based Application in Node.js

Posted on

This is an article where the main subject is actually about how to connet to MySQL Database from a web-based application which runs in NodeJS. The main base of the web-based application project will use the one generated in the article titled ‘How to Create an Express Web-based Framework Application to be deployed in Node.js’ in this link.

So, the following is steps taken in order for the application can connect to MySQL Database.

1. Install MySQL Database package or module in order for the application can have the ability to connect to MySQL Database. In order to view how to install MySQL Database package or module for the application powered by express framework, just read the article titled ‘How to Connect to MySQL Database from a Web-based Application in Node.js’ in this link.

2. Since the main framework is using express, there is also a need to install MySQL Database package or module connection from express framework. To be able to do that, just refer to the article titled ‘How to Install Express MyConnection Package or Module for Web-based Application powered by Express Framework in Node.js’ in this link.

  1. Using the file which is already exists, using the main source generated as a base or skeleton powered by express framework, edit file app.js and add the following snippet code into the file. Just backup the original and recreate the file. And after that, using an empty file named ‘app.js’ just insert the snippet code as follows :
// app.js
const mysql = require('mysql')
const connection = mysql.createConnection({
        host: 'localhost',
        user: 'user',
        password: 'password',
        database: 'db'
});

connection.connect((error) => {
        if(error) throw error;
                console.log("Connected !");
});

Adjust the value which is highlighted as the main parameter for MySQL database connection as shown above based on the environment and settings of MySQL database itself.

4. Execute the file by running the following tool command :

node app.js

The following is the output of the above command execution :

user@hostname:~/nodejs/apps$ node app.js
Connected !
^C
user@hostname:~/nodejs/apps$

The above output is an output generated upon executing the script in the bash prompt or command line. The string “Connected !” will be printed in the bash prompt as the standard output media which is used by ‘console.log’ line of code.

Leave a Reply