API Reference

mysql2

Fast MySQL driver for Node.js with prepared statements, connection pooling and a promise API.

Official Documentation ↗
CompatibilityThis documentation covers version mysql2 v3.x / MySQL 8.0+ / Node 18 LTS. Check the official docs for the latest API surface.

Installation

npmnpm install mysql2
pnpmpnpm add mysql2
yarnyarn add mysql2

Methods

Overview

mysql2 is a MySQL driver with both callback and promise interfaces, prepared statements, and connection pooling. It is commonly used directly or as the engine under an ORM.

Core Methods

createPool returns a pool whose execute method runs parameterized queries and returns rows and fields. For multi-statement work, acquire a connection and use beginTransaction, commit and rollback.

Usage Notes

Use a pool sized to the database limits, always bind parameters, and release connections promptly. Wrap related writes in transactions so partial failures cannot corrupt data.

Common Pitfalls

Forgetting to release a connection from the pool leaks capacity and can stall the app. Buffered queries on huge tables consume memory. Mismatched types between JavaScript and MySQL columns cause subtle errors, so define schemas carefully.

FAQ

Should I use query or execute?
Use execute for parameterized statements because it prepares them server-side and avoids SQL injection. query is for statements that cannot be prepared, such as some DDL.
How does the connection pool work?
createPool keeps a set of reusable connections bounded by connectionLimit. Acquire with getConnection for transactions and always release in a finally block.
How are large result sets handled?
By default rows are buffered into memory. For very large result sets use a non-buffered query or a streaming API so the process does not hold everything at once.