A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/node-js/how-to-connect-node-js-application-to-mysql/ below:

How to Connect Node.js Application to MySQL ?

How to Connect Node.js Application to MySQL ?

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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4