Synchronous MySQL Client

3.0.1 · maintenance · verified Wed Apr 22

sync-mysql is a Node.js library that provides a synchronous interface for interacting with MySQL databases. Unlike most Node.js database drivers which are asynchronous and non-blocking, this package executes SQL queries in a blocking manner, making it suitable for simple scripts, command-line tools, initial setup routines, or test environments where blocking the event loop is acceptable or desired, rather than high-concurrency server applications. The current stable version is 3.0.1, published in late 2022. The release cadence is very slow, with significant gaps between major versions, suggesting a maintenance-only status. Its key differentiator is its synchronous API, which simplifies sequential database operations at the cost of Node.js's typical non-blocking benefits.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates establishing a synchronous MySQL connection, creating a table, inserting data, querying it, and performing a simple calculation, all in a blocking manner. It includes basic error handling and uses environment variables for sensitive credentials.

const MySql = require('sync-mysql');
const assert = require('assert');

const connection = new MySql({
  host: 'localhost',
  user: process.env.DB_USER ?? 'root',
  password: process.env.DB_PASSWORD ?? 'secret',
  database: process.env.DB_NAME ?? 'test_db'
});

try {
  const createTableResult = connection.query('CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))');
  console.log('Table creation result:', createTableResult);

  const insertResult = connection.query("INSERT INTO users (name) VALUES (?) ", ['Alice']);
  console.log('Insert result:', insertResult);
  assert(insertResult.insertId > 0, 'User should be inserted');

  const selectResult = connection.query('SELECT * FROM users WHERE id = ?', [insertResult.insertId]);
  console.log('Select result:', selectResult);
  assert(selectResult.length === 1, 'Should find the inserted user');
  assert(selectResult[0].name === 'Alice', 'User name should be Alice');

  const solution = connection.query('SELECT 1 + 1 AS solution');
  assert(solution[0].solution === 2, 'Basic calculation failed');
  console.log('Synchronous queries executed successfully.');

  connection.end(); // It's good practice to end the connection when done.
} catch (error) {
  console.error('An error occurred:', error.message);
  // Ensure connection is ended even on error
  if (connection && typeof connection.end === 'function') {
    connection.end();
  }
  process.exit(1);
}

view raw JSON →