Registry / database / mysql2

mysql2

JSON →
library3.22.1jsnpmunverified

mysql2 is a high-performance, native JavaScript MySQL client for Node.js, currently stable at version 3.22.1. It provides a robust and efficient way to interact with MySQL databases, emphasizing speed through a re-written protocol parser. The library maintains broad API compatibility with the popular 'Node MySQL' package while introducing advanced features such as comprehensive prepared statement support, binary log protocol, SSL/TLS encryption, and data compression. It also includes a first-class promise-based API wrapper for modern async/await patterns. mysql2 is under active development with a rapid release cadence, frequently pushing out bug fixes, performance improvements, and new features, including recent security enhancements like disabling the `mysql_clear_password` plugin by default and supporting `Symbol.dispose` for resource management.

npm install mysql2
INSTALL
IMPORT
SIG · MYSQL2
M
mysql2
databasejavascriptv3.22.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createConnection
import { createConnection } from 'mysql2';
const createConnection = require('mysql2').createConnection;
For direct connections, less common than pooling in production. Use the promise wrapper for async/await.
createPool
import { createPool } from 'mysql2';
const createPool = require('mysql2').createPool;
Standard way to manage database connections in Node.js applications.
mysql/promise
import mysql from 'mysql2/promise';
import { createConnection, createPool } from 'mysql2/promise';
This specific import provides the promise-based API for `createConnection`, `createPool`, etc. It's a default export of an object containing the promise-wrapped functions.
Connection (type)
import type { Connection } from 'mysql2';
Type import for explicit type annotations in TypeScript. Connection and Pool types are often used.

This quickstart demonstrates how to establish a connection pool, execute a prepared statement for inserting data, and query for data using the `mysql2/promise` API with async/await, and proper resource management.

import mysql from 'mysql2/promise'; import { RowDataPacket, OkPacket, ResultSetHeader } from 'mysql2'; async function runExample() { const pool = mysql.createPool({ host: process.env.DB_HOST ?? 'localhost', user: process.env.DB_USER ?? 'root', password: process.env.DB_PASSWORD ?? 'password', database: process.env.DB_DATABASE ?? 'test_db', waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); try { // Create a table if it doesn't exist await pool.execute<ResultSetHeader>(` CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL ) `); console.log('Table "users" ensured.'); // Insert a new user using a prepared statement const name = 'Alice'; const email = 'alice@example.com'; const [insertResult] = await pool.execute<OkPacket>( 'INSERT INTO users (name, email) VALUES (?, ?)', [name, email] ); console.log(`Inserted user with ID: ${insertResult.insertId}`); // Select users const [rows] = await pool.execute<RowDataPacket[]>('SELECT id, name, email FROM users WHERE name = ?', [name]); if (rows.length > 0) { console.log('Found users:'); rows.forEach(row => { console.log(`- ID: ${row.id}, Name: ${row.name}, Email: ${row.email}`); }); } else { console.log(`No user found with name: ${name}`); } } catch (error) { console.error('Database operation failed:', error); } finally { // Ensure the pool is closed when done await pool.end(); console.log('Database pool closed.'); } } runExample();
Debug
Known issues
breakingThe `mysql_clear_password` authentication plugin is now disabled by default for enhanced security. Users relying on this plugin must explicitly enable it in connection options if still required.
fix
If needed, set `authPlugins.mysql_clear_password.enabled = true` in your connection or pool options. However, it's recommended to use stronger authentication methods.
affects: >=3.22.0
breakingA regression in async stack trace reporting was introduced by a previous fix and patched in `v3.22.1`. If upgrading from versions between `v3.22.0` and `v3.22.1`, async stack traces might point to incorrect source locations.
fix
Upgrade to `v3.22.1` or later to ensure correct async stack trace reporting.
affects: 3.22.0
breakingSecurity vulnerabilities related to out-of-bounds reads in null-terminated string parsing and potential Denial-of-Service (DoS) from malformed geometry payloads were addressed.
fix
Upgrade to `v3.19.1` or newer to mitigate these security risks.
affects: <3.19.1
gotchaWhen handling `BIGINT` or `DECIMAL` types, Node.js's default number precision limits might lead to data loss. Options like `supportBigNumbers`, `bigNumberStrings`, and `dateStrings` should be carefully configured.
fix
For `BIGINT`, set `supportBigNumbers: true` and `bigNumberStrings: true` in your connection options to receive them as strings. For `DATETIME`/`TIMESTAMP`, consider `dateStrings: true` to avoid JavaScript `Date` object limitations.
affects: >=3.0.0
gotchaFor modern asynchronous code, it is highly recommended to use the promise-based API by importing `mysql2/promise` instead of the callback-based API from `mysql2` directly.
fix
Change your import from `import { createPool } from 'mysql2';` to `import mysql from 'mysql2/promise';` and use `await mysql.createPool(...)` and `await pool.execute(...)`.
affects: >=1.5.0
gotchaWhen using prepared statements with `pool.execute()` or `connection.execute()`, parameter values are passed as an array and correctly escaped. Avoid string concatenation for parameters to prevent SQL injection.
fix
Always use `connection.execute(sql, [values])` or `pool.execute(sql, [values])` for queries with user-supplied data, rather than `connection.query()` with string interpolation.
affects: >=3.0.0
Errors
Common errors & fixes
Error: Can't connect to MySQL server on 'localhost' (111)
The MySQL server is not running, is inaccessible from the client, or network configuration is blocking the connection.
fix
Verify the MySQL server status, check network connectivity, firewall rules, and ensure the `host`, `port` and `bind-address` in your MySQL server configuration allow connections from your application's host.
UnhandledPromiseRejectionWarning: Error: Packet sequence number wrong
This often occurs when the connection state is corrupted, frequently due to unexpected server disconnections, network issues, or sometimes mixing callback and promise APIs on the same connection.
fix
Ensure proper error handling for queries and connection releases. For pooled connections, `pool.execute()` and `pool.query()` should handle connection reuse, but persistent connection issues may indicate server problems or network instability. Consider increasing connection timeout.
TypeError: pool.execute is not a function
You are likely trying to call `execute` on a pool object created using the standard `mysql2` import, not the `mysql2/promise` import.
fix
Change your import statement to `import mysql from 'mysql2/promise';` and create your pool using `mysql.createPool(...)`. The promise API uses `execute` for prepared statements.
Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'youruser'@'localhost' (using password: YES)
Incorrect username or password, or the user lacks permissions to connect from the specified host or access the database.
fix
Double-check your `user`, `password`, and `database` credentials. Ensure the MySQL user exists and has `GRANT` privileges for your application's host and the target database.
Upgrade
Version history
3.22.1latest on npm
Audit
Dependencies
@types/nodeoptionalTypeScript type definitions for Node.js runtime environment, primarily for development.
Agent activity
8 hits · last 30 days
node
8
Resources