MySQL2 Node.js Client

3.22.1 · active · verified Sat Apr 18

mysql2 is a fast MySQL driver for Node.js, implementing the core protocol, prepared statements, SSL, and compression in native JavaScript. It offers an API that is largely compatible with the popular `node-mysql` library but provides enhanced performance and additional features, including native promise support. The current stable version is 3.22.1. The project maintains an active development cycle, regularly releasing patch and minor versions.

Common errors

Warnings

Install

Imports

Quickstart

Connects to a MySQL database, executes a simple arithmetic query and a parameterized query using prepared statements, then logs the results. Uses environment variables for sensitive connection details.

import mysql from 'mysql2/promise';

async function connectAndQuery() {
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST ?? 'localhost',
    user: process.env.DB_USER ?? 'root',
    password: process.env.DB_PASSWORD ?? 'password',
    database: process.env.DB_DATABASE ?? 'testdb'
  });

  try {
    const [rows, fields] = await connection.execute('SELECT 1 + 1 AS solution');
    console.log('The solution is: ', rows[0].solution);

    const [users] = await connection.execute('SELECT id, name FROM users WHERE age > ?', [30]);
    console.log('Users over 30:', users);
  } catch (error) {
    console.error('Error executing query:', error);
  } finally {
    await connection.end();
  }
}

connectAndQuery();

view raw JSON →