Open In App

How to connect Node.js application to MySQL ?

Last Updated : 31 Mar, 2023
Like Article

Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 engine that enables us to use JavaScript outside the browser. Node.js helps us to use build server-side applications using JavaScript. In this article, we will discuss how to connect the Node.js application to MySQL. For connecting the node.js with MySQL database we need a third-party mysql module.


  • First, initialize the node.js project in the particular folder on your machine.
  • Download the mysql module in the project folder.
  • After this create a connection to the database with the createconnection() method of the MySQL module.

The above approach is discussed below:

Step 1: Create a NodeJS Project and initialize it using the following command:

npm init

Step 2: Install the mysql modules using the following command:

npm install mysql

File Structure: Our file structure will look like the following:

Mysql database Structure:



// Importing module
const mysql = require('mysql')
const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "Aayush",
    database: "aayush"
// Connecting to database
connection.connect(function (err) {
    if (err) {
        console.log("Error in the connection")
    else {
        console.log(`Database Connected`)
        connection.query(`SHOW DATABASES`,
            function (err, result) {
                if (err)
                    console.log(`Error executing the query - ${err}`)
                    console.log("Result: ", result)

Run the index.js file using the below command:

node index.js

Console Output:

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads