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 mysql2Verified import paths — ran on the pinned version, not inferred.
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.
If needed, set `authPlugins.mysql_clear_password.enabled = true` in your connection or pool options. However, it's recommended to use stronger authentication methods.
Upgrade to `v3.22.1` or later to ensure correct async stack trace reporting.
Upgrade to `v3.19.1` or newer to mitigate these security risks.
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.
Change your import from `import { createPool } from 'mysql2';` to `import mysql from 'mysql2/promise';` and use `await mysql.createPool(...)` and `await pool.execute(...)`.Always use `connection.execute(sql, [values])` or `pool.execute(sql, [values])` for queries with user-supplied data, rather than `connection.query()` with string interpolation.
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.
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.
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.
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.