Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Connect SQLite3 Database using Node.js ?
Next article icon

How to Connect to a MySQL Database Using the mysql2 Package in Node.js?

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We will explore how to connect the Node.js application to a MySQL database using the mysql2 package. MySQL can be widely used as a relational database and mysql2 provides fast, secure, and easy access to MySQL servers, it can allow you to handle database queries efficiently in Node.js applications. We will cover all possible approaches for establishing the connection and demonstrate each with step-by-step instructions.

These are the following ways to Connect to a MySQL Database Using the mysql2 Package in NodeJS:

Table of Content

  • Basic Connection Approach
  • Using the Promises
  • Using the Connection Pooling

Steps to Connect to a MySQL Database Using the mysql2 Package in Node.js

Step 1: Create the new Node.js project

Open the terminal or command prompt and navigate to the folder where you want to create the project. We can run the following command to initialize the new Node.js project.

mkdir mysql-basic-connection
cd mysql-basic-connection
npm init -y

Project Structure:

Project_structure
Project Strcture

Step 2: Install the required dependencies

We can install the mysql2 package and use the following command.

npm install mysql2

Updated dependencies:

{
"name": "mysql-basic-connection",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"mysql2": "^3.11.2"
}
}

Step 3: Start XAMPP

  • Open XAMPP Control Panel: Launch the XAMPP Control Panel.
  • Start Apache and MySQL: Click on the "Start" buttons for both Apache and MySQL.

Step 4: Access phpMyAdmin

  • Open your web browser: Type http://localhost/phpmyadmin in the address bar and press Enter.
  • Access phpMyAdmin: This will take you to the phpMyAdmin interface.

Step 5: Create the Database and Table

  • Go to the structure and run the following command:
CREATE DATABASE IF NOT EXISTS testdb;

USE testdb;

CREATE TABLE IF NOT EXISTS users (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);

INSERT INTO users(name, email) VALUES
('John Doe', '[email protected]'),
('Jane Smith', '[email protected]'),
('Alice Johnson', '[email protected]'),
('Bob Brown', '[email protected]'),
('Charlie Davis', '[email protected]'),
('Eve White', '[email protected]'),
('Frank Black', '[email protected]'),
('Grace Green', '[email protected]'),
('Hank Blue', '[email protected]'),
('Ivy Yellow', '[email protected]');

Basic Connection Approach

The basic connection approach is a simple and direct method to establish the connection to the MySQL database and execute queries. In this approach, we can create the connection, run queries, and then close the connection once the work is done. This method can be suitable for small projects or when you don't need to run multiple database operations simultaneously.

  • Create the connection: Use the mysql2.createConnection() function to create the connection object by passing the configuration details host, user, password, and database name.
  • Execute a query: Once the connection can be established, use the connection.query() method to execute the SQL queries on the database.
  • Handle errors: Any connection errors are passed as the first parameter of the callback function, and should be handled appropriately.
  • Close the connection: Once you are done querying the database close the connection using the connection.end() to release resources.

Example: This example shows the implementation of the above-explained approach.

JavaScript
// app.js const mysql = require('mysql2');  // Create a connection to the database const connection = mysql.createConnection({   host: 'localhost',   user: 'root',   password: 'mypassword',   database: 'testdb' });  // Connect to the database connection.connect((err) => {   if (err) throw err;   console.log('Connected to MySQL Database!');      // Example query   connection.query('SELECT * FROM users', (err, results, fields) => {     if (err) throw err;     console.log(results);   });    // Close the connection   connection.end(); }); 

Step 6: Run the application

we can use the following command to run the application.

node app.js

Output:

output1
Output

Using the Promises

The promise-based approach can involves the basic connection method by making use of the JavaScript promises. This can allows for the more efficient and readable asynchronous code, especially when you have multiple queries to the execute. Instead of using the callbacks, promises can help avoid the nesting and make it easier to handle the success and failure scenarios using the .then() and .catch() or async/await.

  • Create the connection: Use the mysql2/promise module to create the connection with the promise-based API.
  • Execute queries: Queries are executed using the execute() method, which returns the promise that resolves with the query results.
  • Async/await syntax: We can use the async/await syntax to write the code that looks synchronous but works asynchronously, making it easier to the read and manage.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const mysql = require('mysql2/promise');  async function main() {   try {     // Connect to the database using promises     const connection = await mysql.createConnection({       host: 'localhost',       user: 'root',       password: 'mypassword',       database: 'testdb'     });          console.log('Connected to MySQL Database!');          // Execute a query using promise     const [rows, fields] = await connection.execute('SELECT * FROM users');     console.log('Query Result:', rows);          // Close the connection     await connection.end();   } catch (err) {     console.error('Error:', err);   } }  main(); 

Output:

output1
Output

Using the Connection Pooling

In larger applications, where you need to handle the multiple concurrent database requests efficiently, its better to use the connection pooling. Instead of the creating and closing the connection for the every query and the pool of connections from the pool and returned when the query is finished.

  • Create the connection pool: The connection pool is created using the mysql.createpool(). This pool can maintains the multiple connections that can be reused and reducing the overhead of creating and closing connections frequently.
  • Efficient connection management: The pool manages the set number of the connections (eg: 10), which can be used by different queries. When the query is run then the pool picks an available connection.
  • Execute queries: Queries are executed using the pool.query(). Once the query completes then the connection can be returned to the pool for reuse.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const mysql = require('mysql2');  // Create a connection pool const pool = mysql.createPool({   host: 'localhost',   user: 'root',   password: 'mypassword',   database: 'testdb',   waitForConnections: true,   connectionLimit: 10,   queueLimit: 0 });  // Query the database using a pooled connection pool.query('SELECT * FROM users', (err, results, fields) => {   if (err) throw err;   console.log(results); }); 

Output:

output1
Output

Comparison of the Approaches

Approach

Best Use Case

Advantages

Disadvantages

Basic Connection

Simple applications with the limited queries.

Simple to implement the direct interaction.

Inefficient for the frequent queries and connection overhead.

Promises

Medium applications needing the multiple queries.

Clean async flow, better error handling with promises.

Requires the understanding of the promises or async/await.

Connection Pooling

Large scale applications with high concurrency

Efficient performance, connection reuse, scalability.

More complex setup, needs the careful tuning of the pool limits.

Conclusion

The mysql2 package in the Node.js offers the various ways to connect to and query the MySQL database, each suited for the different types of the applications. The basic connection approach works well for the simple applications, while the promise-based approach can be ideal for the cleaner and more manageable asynchronous code. For the larger and more scalable applications, connection pooling offers the better performance by reusing connections. By choosing the right approach based on the application's needs, we can ensure and effective interaction with the MySQL database.


Next Article
How to Connect SQLite3 Database using Node.js ?

G

geekforgs9hp
Improve
Article Tags :
  • Web Technologies
  • Node.js

Similar Reads

  • How to Connect to a MongoDB Database Using the Node.js Driver ?
    MongoDB is a popular, open-source, NoSQL (non-relational) database that provides high performance, high availability, and easy scalability. Unlike traditional relational databases, MongoDB stores a JSON-like format called BSON (Binary JSON). In this article, we connect the MongoDB database to your b
    4 min read
  • How to Connect to a MongoDB Database Using Node.js
    MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ
    4 min read
  • How to Connect SQLite3 Database using Node.js ?
    Connecting SQLite3 database with Node.js involves a few straightforward steps to set up and interact with the database. SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine, making it ideal for small to medium-sized applications. Here’s how you can connect an
    2 min read
  • How to connect MySQL database using Scala?
    MySQL database connectivity using ScalaIntroduction:Since Scala is interoperable with Java, we can directly work with databases using JDBC. JDBC - Java DataBase Connectivity is a Java API that allows Java code or programs to interact with the database.Scala code blocks or programs similarly use thes
    3 min read
  • How to Create Table in SQLite3 Database using Node.js ?
    Creating a table in an SQLite database using Node.js involves several steps, including setting up a connection to the database, defining the table schema, and executing SQL commands to create the table. SQLite is a lightweight and serverless database that is widely used, especially in applications t
    3 min read
  • Connecting to SQL Database using SQLAlchemy in Python
    In this article, we will see how to connect to an SQL database using SQLAlchemy in Python. To connect to a SQL database using SQLAlchemy we will require the sqlalchemy library installed in our python environment. It can be installed using pip - !pip install sqlalchemyThe create_engine() method of sq
    3 min read
  • How to Create and Use Stored Procedures in MySQL with Node.js?
    Stored procedures in MySQL are very useful in the following ways Regarding the encapsulation of business logic within a database. They can be run multiple times and do not cause a large load on the client-server connection. In this tutorial, we will learn how to create and use stored procedures in M
    3 min read
  • How to Use Connection Pooling with MySQL in Node.js?
    MySQL is one of the most preferred relational databases, While Node.js is another name for JavaScript runtime environment. While assessing a large number of connections in the database in a Node. In this regard, effectiveness in managing them is also a significant determinant when developing and mai
    3 min read
  • How to Connect Node to a MongoDB Database ?
    Connecting Node.js to MongoDB is a common task for backend developers working with NoSQL databases. MongoDB is a powerful, flexible, and scalable database that stores data in a JSON-like format. In this step-by-step guide, we'll walk through the entire process from setting up your development enviro
    6 min read
  • How to Insert and Select Data in SQLite3 Database using Node.js ?
    Inserting and selecting data in an SQLite3 database using Node.js involves connecting to the database, running SQL queries, and handling the results. SQLite is an excellent choice for small to medium-sized applications due to its simplicity and lightweight nature. This guide will walk you through th
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences