Open In App

How to connect Node.js application to MySQL ?

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:



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

Article Tags :