Promise MySQL Wrapper

5.2.0 · maintenance · verified Tue Apr 21

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

const mysql = require('promise-mysql');

async function runDbOperations() {
  let connection; // Declare connection outside try block for finally
  try {
    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_NAME ?? 'test_db'
    });

    console.log('Database connected successfully!');

    // Create a table if it doesn't exist
    await connection.query(`
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(255) UNIQUE NOT NULL
      );
    `);
    console.log('Users table ensured.');

    // Insert a new user
    const insertResult = await connection.query('INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com']);
    console.log('Inserted user:', insertResult.insertId);

    // Select all users
    const users = await connection.query('SELECT * FROM users');
    console.log('Users:', users);

    // Clean up (optional: delete the user for idempotency)
    await connection.query('DELETE FROM users WHERE email = ?', ['alice@example.com']);
    console.log('Cleaned up user.');

  } catch (err) {
    console.error('Database operation failed:', err);
  } finally {
    if (connection) {
      await connection.end();
      console.log('Connection closed.');
    }
  }
}

runDbOperations();

view raw JSON →