MySQL2 Node.js Client
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
-
ER_ACCESS_DENIED_ERROR: Access denied for user 'user'@'host' (using password: YES)
cause Incorrect username, password, or host specified in connection options, or the MySQL user lacks necessary permissions.fixDouble-check your `user`, `password`, and `host` in `mysql.createConnection()` options. Verify user permissions in MySQL using `GRANT` statements. -
Error: connect ECONNREFUSED
cause The MySQL server is not running, or it's not accessible at the specified host and port, possibly due to a firewall.fixEnsure your MySQL server is running. Verify the `host` and `port` in your connection options are correct and that no firewall is blocking the connection. -
Error: Packets out of order. Got: 1 Expected: 4
cause This typically indicates a connection issue, such as the MySQL server closing the connection unexpectedly, an invalid query causing a server error, or a network problem.fixReview recent queries for syntax errors. Ensure the MySQL server is stable. Consider increasing the `wait_timeout` on the MySQL server or implementing a connection pool with `acquireTimeout` in your `mysql2` client. -
Cannot read properties of undefined (reading 'fieldCount')
cause This error often occurs when a query fails or returns an unexpected response, leading to `rows` or `fields` being `undefined` or not in the expected format. It can also happen if the connection drops before a query completes.fixEnsure your query is valid and the connection is stable. Add robust error handling around `await connection.execute()` to catch and log specific database errors.
Warnings
- gotcha The `mysql_clear_password` authentication plugin is disabled by default for security reasons.
- gotcha Large integer values (e.g., `BIGINT`) from MySQL can lose precision when converted to standard JavaScript numbers.
- gotcha MySQL `DATETIME` or `TIMESTAMP` columns are converted to JavaScript `Date` objects, which might lead to timezone issues or unexpected formatting without proper configuration.
- gotcha `mysql2` provides both callback-based and promise-based APIs. Mixing them or incorrectly using `async/await` with callbacks can lead to unhandled errors or unexpected behavior.
Install
-
npm install mysql2 -
yarn add mysql2 -
pnpm add mysql2
Imports
- mysql
import mysql from 'mysql2';
- mysql
import mysql from 'mysql2/promise';
Quickstart
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();