Open In App

How to connect Node.js application to MySQL ?

Improve
Improve
Like Article
Like
Save
Share
Report

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 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:

 

Javascript




// 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")
        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 the index.js file using the below command:

node index.js

Console Output:


Last Updated : 31 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads