Skip to content
Related Articles
Open in App
Not now

Related Articles

How to connect Node.js application to MySQL ?

Improve Article
Save Article
  • Last Updated : 19 Oct, 2021
Improve Article
Save 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.

Approach:

  • First, initialize the node.js project in the particular folder in your machine.
  • Download the mysql module in the project folder.
  • After this create 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:

index.js




// Importing module
var mysql = require('mysql')
  
var 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")
      console.log(err)
    }
    else{
      console.log(`Database Connected`)
      connection.query(`SHOW DATABASES`, 
      function (err, result) {
        if(err)
          console.log(`Error executing the query - ${err}`)
        else
          console.log("Result: ",result) 
      })
    }
})

Run index.js file using below command:

node index.js

Console Output:

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!