How to Connect Node.js Application to MySQL ? (original) (raw)

Last Updated : 12 Jun, 2024

**To connect the Node App to the MySQL database we can utilize the mysql package from Node Package Manager. This module provides **pre-defined methods to **create connections, query execution and perform other database related operations.

**Approach to Connect Node App to MySQL

**Syntax:

const mysql = require('mysql');

// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost', // Host Name
user: 'root', // Database Username
password: 'password', // Database Password
database: 'testdb' // Database Name
});

**Steps to Set Up Node App with MySQL

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

**Example: Basic example demonstrating MySQL connection.

Node ``

// Filename - index.js

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

Conclusion

Connecting a Node.js application to a MySQL database involves installing the mysql package, creating a connection with appropriate credentials, executing queries, and handling results. This setup enables efficient database interactions, allowing Node.js applications to perform CRUD operations seamlessly with MySQL, enhancing functionality and data management capabilities.