{"id":16181,"library":"promise-mysql","title":"Promise MySQL Wrapper","description":"promise-mysql is a Node.js library that provides a promise-based wrapper around the `mysqljs/mysql` driver. It leverages the Bluebird promise library to transform the traditional callback-based API of `node-mysql` into an asynchronous, promise-returning interface, supporting `async/await` patterns. Currently at version 5.2.0, this package has not seen a major release in over four years, with its core dependency, `mysqljs/mysql`, also being largely unmaintained. While it differentiates itself by offering promise support for the widely used `node-mysql` driver, modern applications might opt for `mysql2/promise` for native promise support and better performance and features. Its release cadence has been infrequent, indicating a mature but largely static project.","status":"maintenance","version":"5.2.0","language":"javascript","source_language":"en","source_url":"https://github.com/lukeb-uk/node-promise-mysql","tags":["javascript","promise","performance","promises","promises-a","promises-aplus","async","await","deferred"],"install":[{"cmd":"npm install promise-mysql","lang":"bash","label":"npm"},{"cmd":"yarn add promise-mysql","lang":"bash","label":"yarn"},{"cmd":"pnpm add promise-mysql","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"The core MySQL client library that promise-mysql wraps.","package":"mysql","optional":false},{"reason":"The promise library used internally to promisify the mysql client methods. Modern Node.js versions have native Promises, reducing the need for Bluebird.","package":"bluebird","optional":false}],"imports":[{"note":"The library exports a default object containing all methods. Direct named imports are incorrect. As a CommonJS module, `require` is the canonical way to import.","wrong":"import { createConnection } from 'promise-mysql';","symbol":"createConnection","correct":"import mysql from 'promise-mysql';\nconst connection = await mysql.createConnection(options);"},{"note":"This is a CommonJS module, so `require` is the standard import mechanism. Named imports with `import { ... }` will not work directly.","wrong":"import { createPool } from 'promise-mysql';","symbol":"createPool","correct":"const mysql = require('promise-mysql');\nconst pool = await mysql.createPool(options);"},{"note":"The primary benefit of `promise-mysql` is its promise-based API. While the underlying `mysql` driver supports callbacks, directly using callbacks with `promise-mysql` defeats its purpose and can lead to unhandled promise rejections if errors occur.","wrong":"connection.query('SELECT * FROM users', (err, rows) => {});","symbol":"query","correct":"const [rows, fields] = await connection.query('SELECT * FROM users');"}],"quickstart":{"code":"const mysql = require('promise-mysql');\n\nasync function runDbOperations() {\n  let connection; // Declare connection outside try block for finally\n  try {\n    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_NAME ?? 'test_db'\n    });\n\n    console.log('Database connected successfully!');\n\n    // Create a table if it doesn't exist\n    await connection.query(`\n      CREATE TABLE IF NOT EXISTS users (\n        id INT AUTO_INCREMENT PRIMARY KEY,\n        name VARCHAR(255) NOT NULL,\n        email VARCHAR(255) UNIQUE NOT NULL\n      );\n    `);\n    console.log('Users table ensured.');\n\n    // Insert a new user\n    const insertResult = await connection.query('INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com']);\n    console.log('Inserted user:', insertResult.insertId);\n\n    // Select all users\n    const users = await connection.query('SELECT * FROM users');\n    console.log('Users:', users);\n\n    // Clean up (optional: delete the user for idempotency)\n    await connection.query('DELETE FROM users WHERE email = ?', ['alice@example.com']);\n    console.log('Cleaned up user.');\n\n  } catch (err) {\n    console.error('Database operation failed:', err);\n  } finally {\n    if (connection) {\n      await connection.end();\n      console.log('Connection closed.');\n    }\n  }\n}\n\nrunDbOperations();\n","lang":"javascript","description":"Demonstrates connecting to a MySQL database, performing DDL and DML operations (create table, insert, select, delete), and properly closing the connection using async/await with promise-mysql. Environment variables are used for credentials for security."},"warnings":[{"fix":"For new projects, evaluate `mysql2` which has built-in promise support and is actively maintained. If migrating an existing `promise-mysql` project, be aware of potential API differences with `mysql2`.","message":"This package wraps `mysqljs/mysql` (v2.x), which is largely unmaintained (last update over 4 years ago). For new projects or better performance, consider `mysql2/promise` (v3.x or later) which offers native promise support, prepared statements, and active development.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Ensure consistent promise usage across your codebase. If using `async/await`, the integration is usually seamless, but be mindful of Bluebird-specific promise methods if you delve into advanced promise patterns.","message":"Promise-mysql uses the Bluebird promise library internally. While functional, modern Node.js versions have highly optimized native Promises. Relying on Bluebird adds an extra dependency and can occasionally lead to subtle interop issues or differences in promise behavior compared to native Promises.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Ensure that calls to `mysql.createPool()` are `await`ed or chained with `.then()`, as they now return a Promise that resolves to the pool object. For example, `const pool = await mysql.createPool(options);`.","message":"Upgrading from `promise-mysql` v3 to v4 changed `mysql.createPool` to return a `Promise` directly, rather than the pool object itself. This was a significant shift in the API's asynchronous behavior.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Always use a `try...finally` block when acquiring a connection from a pool to ensure `connection.release()` is called, regardless of whether operations succeed or fail. Example: `let connection; try { connection = await pool.getConnection(); /* ... */ } finally { if (connection) connection.release(); }`.","message":"Connections from a pool *must* be explicitly released back to the pool using `connection.release()` when they are no longer needed. Failing to do so will lead to connection leaks, eventually exhausting the pool and causing 'Too many connections' errors or connection timeouts.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Install the underlying MySQL driver: `npm install mysql` or `yarn add mysql`.","cause":"The `promise-mysql` package is a wrapper and depends on the `mysql` package (specifically `mysqljs/mysql`) as a peer dependency. This error occurs if `mysql` is not installed alongside `promise-mysql`.","error":"Cannot find module 'mysql'"},{"fix":"Ensure your MySQL server is stable and accessible. Check server logs for connection errors. For long-running applications, utilize connection pools (`mysql.createPool`) rather than individual connections (`mysql.createConnection`), as pools inherently handle connection re-establishment and rotation. If `reconnect` is explicitly set to `false`, consider enabling it.","cause":"This error often indicates that the MySQL server unexpectedly closed the connection, possibly due to inactivity timeouts, server restarts, or network issues. While `promise-mysql` has a `reconnect` option (default `true`), persistent connection loss indicates deeper issues.","error":"Error: Connection lost: The server closed the connection."},{"fix":"Verify that `mysql.createConnection()` or `pool.getConnection()` were successfully `await`ed and resolved to a valid connection object. Ensure you are calling `query` on the object returned by these methods. Also, avoid mixing `promise-mysql` with the callback-based `mysqljs/mysql` API directly.","cause":"This usually happens if you're trying to call `query` on an object that isn't a valid `promise-mysql` connection or pool object, or if `connection` itself is `undefined` because `createConnection` or `getConnection` failed or wasn't awaited.","error":"TypeError: connection.query is not a function"}],"ecosystem":"npm"}