Node.js MySQL Connection: Complete Tutorial with Examples

Introduction

Node.js applications often need a database to store and retrieve information. MySQL is a popular relational database that works well with Node.js for building websites, REST APIs, and backend applications.

In this tutorial, you will learn how to connect Node.js with MySQL using the mysql2 package, execute SQL queries, use connection pooling, and handle common connection errors.

What Is a MySQL Connection in Node.js?

A MySQL connection allows a Node.js application to communicate with a MySQL database server. The application sends SQL queries through a database driver, and MySQL returns the results.

For example, an application can retrieve users with a SELECT query or save a new user with an INSERT query.

Common use cases include user management, e-commerce websites, employee systems, and REST APIs.

Prerequisites

Before starting, install Node.js, npm, and MySQL Server. You can verify the installations using:


node -v
npm -v
mysql --version

Create a Node.js Project

Create a project directory and initialize it:


mkdir node-mysql-example
cd node-mysql-example
npm init -y
npm install mysql2 dotenv

The mysql2 package provides MySQL connectivity, parameterized queries, and Promise-based APIs. The dotenv package loads configuration from a .env file.

Create a MySQL Database

Run the following SQL statements in MySQL Workbench or your MySQL client:


CREATE DATABASE node_app;
USE node_app;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO users (name, email)
VALUES
('John', 'john@example.com'),
('Sarah', 'sarah@example.com');

Configure Database Credentials

Create a .env file in the project directory:


DB_HOST=localhost
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=node_app
DB_PORT=3306

Replace your_password with your MySQL password. Add .env to .gitignore so credentials are not committed to your repository.

Create a MySQL Connection

Create an app.js file:


require('dotenv').config();
const mysql = require('mysql2/promise');

async function connectDatabase() {
    const connection = await mysql.createConnection({
        host: process.env.DB_HOST,
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME,
        port: Number(process.env.DB_PORT || 3306)
    });

    console.log('Connected to MySQL');
    return connection;
}

connectDatabase()
    .then(connection => connection.end())
    .catch(error => {
        console.error('Database connection failed:', error.message);
        process.exitCode = 1;
    });

Run the application:


node app.js

If the configuration is correct, the terminal displays Connected to MySQL.

The example uses mysql2/promise, which allows database operations to work with async and await.

Execute a SELECT Query

You can retrieve records using the execute() method:


require('dotenv').config();
const mysql = require('mysql2/promise');

async function getUsers() {
    const connection = await mysql.createConnection({
        host: process.env.DB_HOST,
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME
    });

    try {
        const [rows] = await connection.execute(
            'SELECT id, name, email FROM users'
        );

        console.table(rows);
    } finally {
        await connection.end();
    }
}

getUsers().catch(console.error);

The returned rows array contains the matching database records. The finally block closes the connection even if the query fails.

Insert Data Using a Parameterized Query

Use placeholders when passing values into SQL statements:


const [result] = await connection.execute(
    'INSERT INTO users (name, email) VALUES (?, ?)',
    ['David', 'david@example.com']
);

console.log('New user ID:', result.insertId);

The question mark placeholders keep user-provided values separate from the SQL statement, helping prevent SQL injection.

You can use the same approach for updates and deletes:


await connection.execute(
    'UPDATE users SET name = ? WHERE id = ?',
    ['David Smith', 1]
);

await connection.execute(
    'DELETE FROM users WHERE id = ?',
    [1]
);

Use a MySQL Connection Pool

For an Express.js API or an application handling multiple requests, a connection pool is generally preferable to opening a new connection for every request.

A pool manages reusable connections:


const mysql = require('mysql2/promise');
require('dotenv').config();

const pool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    port: Number(process.env.DB_PORT || 3306),
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

async function getUsers() {
    const [rows] = await pool.execute(
        'SELECT id, name, email FROM users'
    );

    return rows;
}

getUsers()
    .then(console.table)
    .catch(console.error);

Unlike a standalone connection, the pool can provide connections for multiple database operations without repeatedly creating them.

For a long-running application, keep the pool available for reuse and close it when the application shuts down.

Common MySQL Connection Errors

Access denied: Check the username, password, and database permissions.

Unknown database: Confirm that node_app exists and that the database name is correct.

Connection refused: Make sure MySQL Server is running and that the hostname and port are correct. The default MySQL port is usually 3306.

Query errors: Check the SQL syntax, table names, column names, and supplied values.

In production, log detailed errors on the server but return generic error messages to API clients.

Best Practices

  • Store credentials in environment variables or a secure configuration system.
  • Use parameterized queries instead of concatenating user input into SQL.
  • Prefer connection pooling for APIs and applications handling concurrent requests.
  • Handle connection and query errors.
  • Give the database user only the permissions the application needs.
  • Close standalone connections when finished.
  • Never commit secrets to a public repository.

Conclusion

The mysql2 package provides a straightforward way to connect Node.js applications to MySQL databases. You can execute SQL queries using its callback or Promise-based APIs, while connection pooling is a practical choice for Express.js APIs and larger applications.

Use environment variables, parameterized queries, and proper error handling to make database connections safer and easier to maintain.