How to connect Node.js to MySQL

Connecting Node.js to MySQL provides robust relational database capabilities for applications requiring structured data storage and complex queries. As the creator of CoreUI with extensive Node.js experience since 2014, I’ve integrated MySQL with Node.js in numerous enterprise applications for e-commerce and business management systems. The most reliable approach uses the mysql2 library with connection pooling for optimal performance and modern JavaScript support. This method ensures secure, efficient database access while supporting both callback and promise-based patterns.

Use mysql2 library with connection pooling to establish secure and performant MySQL connections.

const mysql = require('mysql2/promise')

class MySQLConnection {
    constructor() {
        this.pool = mysql.createPool({
            host: process.env.DB_HOST || 'localhost',
            port: process.env.DB_PORT || 3306,
            user: process.env.DB_USER || 'root',
            password: process.env.DB_PASSWORD,
            database: process.env.DB_NAME || 'myapp',
            waitForConnections: true,
            connectionLimit: 10,
            queueLimit: 0,
            acquireTimeout: 60000,
            timeout: 60000
        })
    }

    async query(sql, params) {
        try {
            const [rows, fields] = await this.pool.execute(sql, params)
            return rows
        } catch (error) {
            console.error('Database query error:', error)
            throw error
        }
    }

    async getConnection() {
        return await this.pool.getConnection()
    }

    async close() {
        await this.pool.end()
        console.log('MySQL connection pool closed')
    }
}

// Usage
const db = new MySQLConnection()

async function initializeApp() {
    try {
        // Test connection
        const result = await db.query('SELECT NOW() as current_time')
        console.log('Database connected:', result[0].current_time)

        // Example query with parameters
        const users = await db.query(
            'SELECT * FROM users WHERE email = ?',
            ['[email protected]']
        )
        console.log('Users found:', users)

    } catch (error) {
        console.error('Database initialization error:', error)
    }
}

initializeApp()

// Graceful shutdown
process.on('SIGTERM', async () => {
    await db.close()
    process.exit(0)
})

This code creates a MySQL connection pool using mysql2 with proper configuration for production environments. The connection class provides query methods with parameter binding to prevent SQL injection, along with connection management and graceful shutdown handling. The pool automatically manages connections for optimal performance.

Best Practice Note:

This is the MySQL connection architecture we use in CoreUI enterprise backend services for reliable data management. Always use parameterized queries to prevent SQL injection and implement proper connection pooling to handle concurrent requests efficiently.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author