{"id":16544,"library":"sync-mysql","title":"Synchronous MySQL Client","description":"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.","status":"maintenance","version":"3.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/ForbesLindesay/sync-mysql","tags":["javascript"],"install":[{"cmd":"npm install sync-mysql","lang":"bash","label":"npm"},{"cmd":"yarn add sync-mysql","lang":"bash","label":"yarn"},{"cmd":"pnpm add sync-mysql","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core underlying MySQL driver wrapped by sync-mysql for database communication.","package":"mysql","optional":false}],"imports":[{"note":"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.","wrong":"import MySql from 'sync-mysql';","symbol":"MySql","correct":"const MySql = require('sync-mysql');"},{"note":"Always pass dynamic values as the second argument to `query` to prevent SQL injection, rather than concatenating strings directly into the query string.","wrong":"connection.query('SELECT ' + someVar)","symbol":"connection.query","correct":"connection.query('SELECT 1')"},{"note":"The `getRecord` method expects the table name as the first argument and the ID as the second, assuming a column named 'id'.","wrong":"const record = connection.getRecord('users', { id: 1 });","symbol":"connection.getRecord","correct":"const record = connection.getRecord('users', 1);"}],"quickstart":{"code":"const MySql = require('sync-mysql');\nconst assert = require('assert');\n\nconst connection = new MySql({\n  host: 'localhost',\n  user: process.env.DB_USER ?? 'root',\n  password: process.env.DB_PASSWORD ?? 'secret',\n  database: process.env.DB_NAME ?? 'test_db'\n});\n\ntry {\n  const createTableResult = connection.query('CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))');\n  console.log('Table creation result:', createTableResult);\n\n  const insertResult = connection.query(\"INSERT INTO users (name) VALUES (?) \", ['Alice']);\n  console.log('Insert result:', insertResult);\n  assert(insertResult.insertId > 0, 'User should be inserted');\n\n  const selectResult = connection.query('SELECT * FROM users WHERE id = ?', [insertResult.insertId]);\n  console.log('Select result:', selectResult);\n  assert(selectResult.length === 1, 'Should find the inserted user');\n  assert(selectResult[0].name === 'Alice', 'User name should be Alice');\n\n  const solution = connection.query('SELECT 1 + 1 AS solution');\n  assert(solution[0].solution === 2, 'Basic calculation failed');\n  console.log('Synchronous queries executed successfully.');\n\n  connection.end(); // It's good practice to end the connection when done.\n} catch (error) {\n  console.error('An error occurred:', error.message);\n  // Ensure connection is ended even on error\n  if (connection && typeof connection.end === 'function') {\n    connection.end();\n  }\n  process.exit(1);\n}\n","lang":"javascript","description":"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."},"warnings":[{"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.","message":"The `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.","severity":"breaking","affected_versions":">=1.0.0"},{"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])`.","message":"Incorrectly 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The 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.","severity":"deprecated","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"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.","cause":"The MySQL server is not running, is inaccessible from the specified host, or the port is incorrect.","error":"Error: connect ECONNREFUSED"},{"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.","cause":"Attempted to use `MySql` without correctly requiring it or using a named import when it's a default export.","error":"TypeError: MySql is not a constructor"},{"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])`.","cause":"A placeholder `?` was used in the SQL query string, but no array of values was provided as the second argument to `connection.query()`.","error":"Error: Query arguments required (for parameterized query)"},{"fix":"Add `const assert = require('assert');` at the top of your script to make the `assert` function available.","cause":"The `assert` module used in quickstart examples is a built-in Node.js module but needs to be explicitly required.","error":"ReferenceError: assert is not defined"}],"ecosystem":"npm"}