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.
npm install sync-mysqlVerified import paths — ran on the pinned version, not inferred.
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.
For high-performance, asynchronous Node.js applications, use a standard promise-based or callback-based MySQL driver (e.g., `mysql2`, `node-mysql`). `sync-mysql` is best reserved for simple scripts, CLI tools, or tests where blocking is acceptable.
Always use parameterized queries by passing an array of values as the second argument to `connection.query(sql, values)`. Example: `connection.query('SELECT * FROM users WHERE id = ?', [userId])`.For applications requiring connection pooling or robust connection management, prefer asynchronous drivers that offer these features. If `sync-mysql` must be used, consider manual connection management and reconnection logic, though this often defeats the simplicity goal of a synchronous library.
Consider migrating to `mysql2` with its promise wrapper for a modern, actively maintained, and performant asynchronous MySQL driver that supports `async/await` and provides official TypeScript definitions.
Ensure your MySQL server is running, check the `host` and `port` in your connection configuration, and verify no firewall is blocking the connection. For Docker, ensure the database container is healthy and ports are exposed correctly.
Use `const MySql = require('sync-mysql');` to correctly import the class. If using ESM, consider if `sync-mysql` is the right tool or if a CommonJS wrapper is needed.Always provide an array of values as the second argument to `connection.query()` when using `?` placeholders. Example: `connection.query('SELECT * FROM users WHERE id = ?', [123])`.Add `const assert = require('assert');` at the top of your script to make the `assert` function available.