{"id":10403,"library":"mysql2","title":"MySQL2 Node.js Client","description":"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.","status":"active","version":"3.22.1","language":"javascript","source_language":"en","source_url":"https://github.com/sidorares/node-mysql2","tags":["javascript","mysql","client","server","typescript"],"install":[{"cmd":"npm install mysql2","lang":"bash","label":"npm"},{"cmd":"yarn add mysql2","lang":"bash","label":"yarn"},{"cmd":"pnpm add mysql2","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For callback-based API and general utilities.","symbol":"mysql","correct":"import mysql from 'mysql2';"},{"note":"For the promise-based API, recommended for modern applications.","symbol":"mysql","correct":"import mysql from 'mysql2/promise';"}],"quickstart":{"code":"import mysql from 'mysql2/promise';\n\nasync function connectAndQuery() {\n  const connection = await mysql.createConnection({\n    host: process.env.DB_HOST ?? 'localhost',\n    user: process.env.DB_USER ?? 'root',\n    password: process.env.DB_PASSWORD ?? 'password',\n    database: process.env.DB_DATABASE ?? 'testdb'\n  });\n\n  try {\n    const [rows, fields] = await connection.execute('SELECT 1 + 1 AS solution');\n    console.log('The solution is: ', rows[0].solution);\n\n    const [users] = await connection.execute('SELECT id, name FROM users WHERE age > ?', [30]);\n    console.log('Users over 30:', users);\n  } catch (error) {\n    console.error('Error executing query:', error);\n  } finally {\n    await connection.end();\n  }\n}\n\nconnectAndQuery();","lang":"typescript","description":"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."},"warnings":[{"fix":"If required for legacy systems, explicitly enable it in your connection options: `{ authPlugins: { mysql_clear_password: () => true } }`. Consider using more secure authentication methods where possible.","message":"The `mysql_clear_password` authentication plugin is disabled by default for security reasons.","severity":"gotcha","affected_versions":">=3.22.0"},{"fix":"Use `supportBigNumbers: true` and `bigNumberStrings: true` in your connection options to receive large numbers as strings, preventing precision loss: `{ supportBigNumbers: true, bigNumberStrings: true }`.","message":"Large integer values (e.g., `BIGINT`) from MySQL can lose precision when converted to standard JavaScript numbers.","severity":"gotcha","affected_versions":"*"},{"fix":"Use `dateStrings: true` in connection options to retrieve dates as MySQL string format directly, or specify a `timezone` (e.g., `'Z'` for UTC) for consistent `Date` object conversion: `{ dateStrings: true }` or `{ timezone: 'Z' }`.","message":"MySQL `DATETIME` or `TIMESTAMP` columns are converted to JavaScript `Date` objects, which might lead to timezone issues or unexpected formatting without proper configuration.","severity":"gotcha","affected_versions":"*"},{"fix":"For modern Node.js applications, prefer the promise-based API by importing `mysql2/promise`. Ensure all database operations are `await`ed within `async` functions or handled with `.then().catch()`.","message":"`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.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-18T00:00:00.000Z","next_check":"2026-07-17T00:00:00.000Z","problems":[{"fix":"Double-check your `user`, `password`, and `host` in `mysql.createConnection()` options. Verify user permissions in MySQL using `GRANT` statements.","cause":"Incorrect username, password, or host specified in connection options, or the MySQL user lacks necessary permissions.","error":"ER_ACCESS_DENIED_ERROR: Access denied for user 'user'@'host' (using password: YES)"},{"fix":"Ensure your MySQL server is running. Verify the `host` and `port` in your connection options are correct and that no firewall is blocking the connection.","cause":"The MySQL server is not running, or it's not accessible at the specified host and port, possibly due to a firewall.","error":"Error: connect ECONNREFUSED"},{"fix":"Review 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.","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.","error":"Error: Packets out of order. Got: 1 Expected: 4"},{"fix":"Ensure your query is valid and the connection is stable. Add robust error handling around `await connection.execute()` to catch and log specific database errors.","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.","error":"Cannot read properties of undefined (reading 'fieldCount')"}],"ecosystem":"npm"}