Node-RED MySQL Database Connector
This package provides a Node-RED node for connecting to and interacting with MySQL databases. It allows users to execute SQL `query` operations, including `INSERT`, `UPDATE`, `DELETE`, and `SELECT` statements, by passing the SQL query in `msg.topic` and parameters in `msg.payload`. The results are returned in `msg.payload`, typically as an array of rows or null if no results are found. The current stable version is 3.0.0. While a specific release cadence isn't published, the project maintains an active development presence on GitHub. A key differentiator is its seamless integration into the Node-RED visual programming environment, abstracting direct `mysql` library usage into a configurable, GUI-driven node. It supports parameterized queries, both positional and named, which helps mitigate basic SQL injection risks, but explicitly warns users to remain vigilant about security. The node also offers configuration options for database reconnection timeouts and character sets.
Common errors
-
ER_ACCESS_DENIED_ERROR: Access denied for user 'user'@'host' (using password: YES/NO)
cause Incorrect database username, password, or host provided in the MySQL node configuration.fixVerify the database credentials (username, password, host, port) in the Node-RED MySQL node configuration against your MySQL server settings. Ensure the user has the necessary permissions. -
ER_BAD_DB_ERROR: Unknown database 'your_database_name'
cause The database name configured in the Node-RED MySQL node does not exist on the specified MySQL server.fixCorrect the database name in the Node-RED MySQL node configuration, or create the database on your MySQL server if it's missing. -
UnhandledPromiseRejectionWarning: Connection lost: The server closed the connection.
cause The connection to the MySQL server was unexpectedly closed, often due to server-side timeouts, network issues, or the MySQL server being restarted.fixCheck the MySQL server's status and network connectivity. In the Node-RED MySQL node configuration, you can adjust the `mysqlReconnectTime` setting (in `settings.js`) to control the retry timeout for reconnecting. -
SyntaxError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '...' at line X
cause The SQL query provided in `msg.topic` contains a syntax error, or includes invalid characters/keywords for your specific MySQL version.fixCarefully review the SQL query string in your Node-RED Function node (or wherever `msg.topic` is set). Test the query directly in a MySQL client to isolate and fix syntax issues. Ensure parameterized queries are correctly formatted.
Warnings
- gotcha The node explicitly states that by its nature it allows SQL injection. Users are solely responsible for sanitizing input and constructing safe queries. While parameterized queries (`?` or `:name`) are supported and recommended, misuse or direct concatenation of untrusted input can lead to severe security vulnerabilities.
- breaking As of version 3.0.0, the package requires Node.js version 18.0.0 or higher. Running on older Node.js environments will result in errors.
- gotcha The default character set used by the MySQL connection is often 'old' Mysql 3-byte UTF. If your application needs to handle emojis or extended Unicode characters, you must explicitly configure the database and the connection to use `UTF8MB4`.
- gotcha The README mentions that `null` is returned if nothing is found for a key. However, database operations can fail for many other reasons (connection errors, SQL syntax errors, permissions). Without explicit error handling within the Node-RED flow (e.g., wiring the error output of the MySQL node), these failures can go unnoticed.
Install
-
npm install node-red-node-mysql -
yarn add node-red-node-mysql -
pnpm add node-red-node-mysql
Imports
- Node-RED MySQL Node
This package is a Node-RED node, installed via the Node-RED palette manager or `npm i node-red-node-mysql` in your Node-RED user directory. It does not expose symbols for direct JavaScript `import` or `require` by end-user applications; interaction occurs graphically within the Node-RED editor by dragging and configuring the 'MySQL' node.
Quickstart
{
"id": "b1c2d3e4.f5g6h7",
"type": "function",
"name": "Prepare MySQL Query",
"func": "// This code is designed to be placed inside a Node-RED Function node.\n// It prepares the 'msg.topic' and 'msg.payload' objects\n// which are then passed to a `MySQL` database node (from this package).\n\n// First, ensure you have a `MySQL` node configured in your Node-RED flow\n// with appropriate database credentials and connection details.\n// Connect the output of this Function node to the input of your MySQL node.\n\n// Example: Inserting a new user with a unique username\n// Make sure your 'users' table exists, e.g.:\n// CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) UNIQUE NOT NULL);\n\nconst uniqueUsername = `user_${Date.now()}_${Math.floor(Math.random() * 1000)}`;\nmsg.payload = { username: uniqueUsername };\nmsg.topic = \"INSERT INTO users (username) VALUES (:username);\";\n\n// --- Alternative: Updating an existing user ---\n// Uncomment the following lines to demonstrate an update operation.\n// This requires a user with a specific ID to exist.\n/*\nmsg.payload = { userId: 1, newUsername: \"updated_user_name\" };\nmsg.topic = \"UPDATE users SET username = :newUsername WHERE id = :userId;\";\n*/\n\n// --- Alternative: Selecting data ---\n// Uncomment the following lines to demonstrate a select operation.\n/*\nmsg.payload = { searchTerm: \"%user%\" };\nmsg.topic = \"SELECT id, username FROM users WHERE username LIKE :searchTerm;\";\n*/\n\nreturn msg;",
"outputs": 1,
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 100,
"y": 100,
"wires": [
[
"a8b9c0d1.e2f3g4" // Connect this to your Node-RED MySQL node's ID
]
]
}