Registry / database / sync-mysql

sync-mysql

JSON →
library3.0.1jsnpmunverified

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-mysql
INSTALL
IMPORT
SIG · SYNC-MYSQL
S
sync-mysql
databasejavascriptv3.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MySql
const MySql = require('sync-mysql');
import MySql from 'sync-mysql';
The library primarily uses CommonJS `require()` syntax. It exports the `MySql` class as a default export, not named. ESM `import` is not officially supported or documented and may not work without transpilation.
connection.query
connection.query('SELECT 1')
connection.query('SELECT ' + someVar)
Always pass dynamic values as the second argument to `query` to prevent SQL injection, rather than concatenating strings directly into the query string.
connection.getRecord
const record = connection.getRecord('users', 1);
const record = connection.getRecord('users', { id: 1 });
The `getRecord` method expects the table name as the first argument and the ID as the second, assuming a column named 'id'.

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); }
Debug
Known issues
breakingThe `sync-mysql` library performs synchronous I/O operations, which fundamentally blocks the Node.js event loop. This makes it unsuitable for server applications or any context requiring high concurrency, as it will halt all other processing until database operations complete. While not an API breaking change, adopting this library in an asynchronous Node.js application is a architectural anti-pattern and will lead to severe performance bottlenecks.
fix
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.
affects: >=1.0.0
gotchaIncorrectly concatenating strings into SQL queries can lead to severe SQL injection vulnerabilities. While `sync-mysql` provides parameterized queries via the second argument to `connection.query()`, developers might mistakenly build queries with string concatenation.
fix
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])`.
affects: >=1.0.0
gotchaThe `sync-mysql` library does not natively support connection pooling or automatic reconnection strategies, common in modern database drivers. This can lead to issues with resource exhaustion or dropped connections over time in long-running processes.
fix
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.
affects: >=1.0.0
deprecatedThe library shows a very slow development cadence, with the last major release (v3.0.0) primarily bumping dependencies and fixing security vulnerabilities rather than adding significant new features or modernizing the API. It lacks features like async/await support, promise-based APIs, or robust TypeScript typings that are standard in modern Node.js ecosystems.
fix
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.
affects: >=1.0.0
Errors
Common errors & fixes
Error: connect ECONNREFUSED
The MySQL server is not running, is inaccessible from the specified host, or the port is incorrect.
fix
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.
TypeError: MySql is not a constructor
Attempted to use `MySql` without correctly requiring it or using a named import when it's a default export.
fix
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.
Error: Query arguments required (for parameterized query)
A placeholder `?` was used in the SQL query string, but no array of values was provided as the second argument to `connection.query()`.
fix
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])`.
ReferenceError: assert is not defined
The `assert` module used in quickstart examples is a built-in Node.js module but needs to be explicitly required.
fix
Add `const assert = require('assert');` at the top of your script to make the `assert` function available.
Upgrade
Version history
3.0.1latest on npm
Audit
Dependencies
mysqlrequiredCore underlying MySQL driver wrapped by sync-mysql for database communication.
Agent activity
20 hits · last 30 days
node
16
Meta
2
OpenAI (training)
1
Resources