Skip to content

All topics  /  Node.js

How to Check DB Connection in Node.js?

Node.js ·

For teams turning “How to Check DB Connection in Node.js?” into a repeatable delivery task, hr effectiveness can document setup, troubleshooting and review time; managers should interpret those records alongside reliability and completed work, not as a stand-alone score.

Package and operating-system behaviour can change, so verify the commands and supported versions through the Node.js project before running them on a production host.

Hello Friends,

This article will provide an example of how to check DB connection in node.js. We will look at an example of check db connection in nodejs. Here you will learn to check db connection in node js. if you want to see an example of node.js check db connection then you are the right place.

In this tutorial, we will show you how to use node.js driver for MySQL called mysqljs/mysql. In this example to access a MySQL database with Node.js, you need a MySQL driver. I will explain simple connected db MySQL with nodejs.

So, le't start following example:

Step 1: Install Node JS

This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app
cd my-app
npm init

Install node.js for MySQL package by using the following command:

Step 2: npm install mysql

We will use the node_app database for demonstration, therefore, you should create the database in your MySQL database server by running the following CREATE DATABASE statement:

CREATE DATABASE node_app;

Database is created, you are ready to connect to it from the Node.js application.

Step 3: Update server.js File

server.js

var mysql = require('mysql');
// setup your databse (username & password & databasename)
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'node_app'
});
// check your database connection
connection.connect(function(err) {
    if (err) {
        return console.error('error: ' + err.message);
    }
    console.log('Connected to the MySQL server.');
});

Run Node App:

node server.js    

Output:

Connected to the MySQL server.

I hope it can help you...

# Node JS