How To Connect MySQL Database in Node Js Application

Share this Article
Reading Time: 5 minutes
420 Views

Inside this article we will see how to connect mysql database in node js application. This will be very easy process to add and implement into node application.

Tutorial assumes that in your system node and npm both successfully installed.

Node JS is an environment where we can deploy and execute javascript based applications. In this article we will connect mysql database with it.

MySQL will be a npm package for this node application. How can we use MySQL NPM package for database and all we will see inside this tutorial.

Learn More –

Let’s get started.


Node Js Application Setup

Please make sure you have node and npm both installed. To check available versions use these commands.

To check node version

$ node -v

To check npm version

$ npm -v

Create a folder with any name say mysql-connection. Open this folder into terminal or command prompt.

Next, we need package.json file. Run this given command into terminal

$ npm init -y

The given command will auto generate package.json file with default values.

Next we need to create a file say server.js into node application.


Install MySQL Package

Open project in terminal and run this npm command to install mysql.

$ npm install mysql

It will install mysql npm package to application.

Open package.json file to verify –


MySQL Connection & Query Execution

There are few steps we should follow as a beginner to connect with mysql and query execute.

  • Load MySQL package
  • Connect with MySQL
  • Check connection working or not
  • Query Execute

Let’s see all these in action.

Open server.js file from setup and write this complete code into it.

// Load MySQL package
var mysql = require('mysql');

// Open MySQL Connection
var connection = mysql.createConnection({
    host: "localhost",
    database: 'sample_app',
    user: "admin",
    password: "Admin@123"
});

// Checking connection
connection.connect(function(err) {
    if (err) throw err;
    console.log("Successfully connected to database!");
});

// Executing Query
connection.query('SELECT * FROM browser_stats', function(error, results, fields) {
    if (error)
        throw error;

    results.forEach(result => {
        console.log(result);
    });
});

// Connection close
connection.end();

Application Testing

Open project terminal and type this command.

$ node server.js

For this tutorial we have used only a select statement. You can use either insert, update, delete etc.

We hope this article helped you to learn How To Connect MySQL Database in Node Js Application in a very detailed way.

Buy Me a Coffee

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Learn More on MySQL