IMD SolutionComputing LibraryShop main store

How-to

Connect Node-RED on ctrlX CORE to a MySQL server

Edge computing and IIoT Published 7 min read

Short answer

Send the SQL as msg.topic to a node-red-node-mysql node: create the table once as an administrator, prove one INSERT and SELECT from Inject nodes, then route Read Datalayer values into a multi-row insert. Grant the runtime account only SELECT and INSERT on db1, match its host part to the client address the server reports, and keep a local snap's data directory on external media.

On this page
  1. How do you set up MySQL so the controller can connect?
  2. How do you install the MySQL node in Node-RED?
  3. How do you create the table and prove one write?
  4. How do PLC values get into the insert?
  5. Which privileges should the Node-RED account have?
  6. What changes when MySQL runs on the controller as a snap?
  7. What decides whether an outage loses samples or grows a backlog?
  8. Questions asked

Node-RED on ctrlX CORE writes to MySQL through one pattern: a node-red-node-mysql node executes whatever statement arrives in msg.topic, and a Function node builds that statement from your data. The order that works: initialize the server (the example listens on port 3306 with database db1), create the table once as an administrator, prove a standalone INSERT and SELECT from Inject nodes, then connect the Read Datalayer node. Give the runtime account only SELECT and INSERT on db1, with its host part set to the client address the server actually sees. A MySQL snap on the controller itself uses the same flow, with the data directory moved to external media.

How do you set up MySQL so the controller can connect? #

Initialize a new data directory once with mysqld --initialize --console, start the server with mysqld --console, create database db1, and create one application account whose host part is the address the controller connects from; the example server listens on port 3306.

  1. Unpack the portable server package, the example uses mysql-8.0.38-winx64, and work from its bin folder.
  2. Run mysqld --initialize --console once. It creates the system databases and prints a temporary password for root; save it. This is a first-initialization command, not a restart command.
  3. Start the server with mysqld --console and read the console until it reports the listening port.
  4. Open a second terminal in the same folder and connect with mysql -u root -p, entering the temporary password when prompted.
  5. Replace the temporary password, create the database and the runtime account, and grant it what it keeps for deployment. The two passwords and the host below are example values: take credentials from your password manager, and the host from the client address your server reports.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'root-Example-31';
CREATE DATABASE db1;
USE db1;
CREATE USER 'ctrlxcore'@'10.195.70.29' IDENTIFIED BY 'app-Example-31';
GRANT SELECT, INSERT ON db1.* TO 'ctrlxcore'@'10.195.70.29';
  1. On ctrlX CORE Virtual, enable external access and set up the port forwarding your virtual network needs for both the Node-RED interface and the database port, then test the controller's route to the server before building the flow.

How do you install the MySQL node in Node-RED? #

Open the palette manager, search for node-red-node-mysql and press install; then drag a MySQL node into the flow and point it at the server address, the port, database db1 and the runtime credentials.

  1. The palette manager downloads from the public registry, so the controller needs internet access while you install.
  2. Drag a MySQL node into the workspace and open its edit dialog.
  3. Enter the server address, the port, the runtime account's user and password, and database db1, the same values the grant above scoped.
  4. Wire an Inject node through a Function node into the MySQL node, with a Debug node on its output; the next section fills the Function nodes.

How do you create the table and prove one write? #

Create table Drives once from the mysql client as root, then prove the path with two Inject nodes: one whose Function sets msg.topic to a single-row INSERT, one that sets a SELECT; the returned row in msg.payload is the proof.

  1. In the client, still as root, run:
USE db1;
CREATE TABLE Drives (
  id SERIAL PRIMARY KEY,
  device_id VARCHAR(50) NOT NULL,
  timestamp TIMESTAMP NOT NULL,
  velocity FLOAT,
  position FLOAT,
  torque FLOAT,
  status VARCHAR(20)
);

id SERIAL generates the row identifier; device_id and timestamp are mandatory, the three measurement columns are floating point, and status is short text. The runtime account cannot run this statement, and that is intended.

  1. Set the first Function node to:
msg.topic = "INSERT INTO Drives (device_id, timestamp, velocity, position, torque, status) VALUES ('HCS01', NOW(), RAND() * 1000, RAND() * 10000, RAND() * 20, 'OK')";
return msg;
  1. Set the second Function node to:
msg.topic = "SELECT * FROM Drives";
return msg;
  1. Deploy, press the first Inject, then the second: the Debug sidebar shows the stored row set. In the client, SHOW TABLES; lists the table and SHOW COLUMNS FROM Drives; returns the seven field definitions.

Keep the capitalization Drives in every statement. On Linux the default lower_case_table_names of 0 makes table names case-sensitive, so drives and Drives are two different tables; the Windows default of 1 lowercases them and hides the mismatch until the database moves to a Linux host. MySQL 8.0 refuses to change that setting after initialization, so fix the spelling in the statements, not the server.

How do PLC values get into the insert? #

Publish the PLC variable in Symbol Configuration, read it with a Read Datalayer node, and build one multi-row INSERT in a Function node: one VALUES tuple per array element, all sent in a single msg.topic.

  1. In the PLC project, produce the values, the example publishes an array of randomized torque readings, and add the variable to the Symbol Configuration so the data layer exposes it. Load the program and confirm the variable with a Debug node before writing any SQL.
  2. Add a Read Datalayer node, point its device settings at the controller, and enter the path of the published symbol.
  3. Build the statement in a Function node. The example assumes msg.payload is an array of numbers; rows and i are ordinary local variables, while msg.topic and msg.payload are the Node-RED message properties:
var rows = []; // collects one VALUES tuple per reading
for (var i = 0; i < msg.payload.length; i++) {
    rows.push("('HCS01', NOW(), RAND() * 1000, RAND() * 10000, " + msg.payload[i] + ", 'OK')");
}
msg.topic = "INSERT INTO Drives (device_id, timestamp, velocity, position, torque, status) VALUES " + rows.join(",");
return msg;
  1. Prove it with a count: an array of 10 readings produces 10 tuples in one statement, the MySQL node's output reports 10 affected rows, and a following SELECT returns 10 new rows for device HCS01. The multi-row VALUES list is ordinary SQL that MySQL 8.0 executes as one statement.

Which privileges should the Node-RED account have? #

Exactly SELECT and INSERT on db1, as granted above: the flow writes rows and reads them back, so it never needs CREATE, DROP, server-wide rights or the ability to grant; keep those with the administrator.

A grant of ALL PRIVILEGES on all databases WITH GRANT OPTION would hand the flow every schema on the server plus the right to delegate that access, so one wrong edit in a Function node could drop a table it names. Schema changes stay with root at the server console, and the flow keeps the two statements it actually uses.

A MySQL account is a user name plus a host part, and both must match at login. The example account ctrlxcore with host part 10.195.70.29 accepts no login from any other address, and the same user name with a different host is a different account. When a login is rejected, the server's message names the client address it saw; with a virtual controller or address translation in the path, that address can differ from the controller's own, so create the account for the reported address, not the assumed one.

What changes when MySQL runs on the controller as a snap? #

Only the connection and the storage: the snap keeps the same msg.topic flow, provisions its own account for the loopback address, and must keep its data directory on external media, because the controller's internal storage has limited capacity and write lifetime.

The install hook writes that account on first start, for example:

CREATE USER IF NOT EXISTS 'ctrlxcore_auto'@'127.0.0.1' IDENTIFIED BY 'app-Example-32';

Mount the USB media in Settings>Storage, the example mount path is /media/sdb1, and give the mysqld app in snapcraft.yaml the removable-media and hardware-observe plugs so the confined snap can reach it. The wrapper snap/local/bin/mysqld.sh migrates on first run: when mysql.ibd exists in the internal data directory and not yet on the media, it copies the database across, sets ownership for snap_daemon, and starts the server with --datadir on the media; when neither location holds an initialized directory it stops with an error instead of booting an empty one. The same storage constraint is why InfluxDB on ctrlX OS only offers external storage. On anything beyond a bench test, run with the data directory on the mounted media and treat the internal copy as a first-boot seed.

What decides whether an outage loses samples or grows a backlog? #

Your flow design decides it: the MySQL node returns an error when the send fails, and nothing is retried unless a buffer sits ahead of the database node, so an unbuffered flow loses the samples of an outage.

Keep the database work out of the PLC program: SQL has no place in the control cycle, and the Read Datalayer node already samples on its own schedule. In the flow, queue messages while the connection is down, write them out on reconnect, and cap the queue. Size the cap from the logging rate: at 1 message per second, a 10-minute outage queues 10 x 60 = 600 messages, so set cap and retention together before the first outage, not during it. The queue-on-outage pattern is worked through in store-and-forward SQL buffering during MES outages.

Questions asked

Is FLUSH PRIVILEGES needed after creating the account and grant?

No. CREATE USER and GRANT update the grant tables and apply to new connections immediately; FLUSH PRIVILEGES exists for changes made directly to those tables with statements such as INSERT. Running it anyway does no harm on a small server, but it is not what activates the account; the grant alone is enough.

Can the insert use parameters instead of a built string?

Yes. node-red-node-mysql treats placeholders as named parameters when msg.payload is an object: a statement such as INSERT INTO users (userid, username) VALUES (:id, :name) takes each value from the payload key with the same name. That keeps values out of the SQL text and is the form to switch to as soon as a value is a string rather than a number.

Why does the root login work at the server console but fail from Node-RED?

The root account in the example is defined for localhost only, so a TCP connection from the controller is refused whatever password is sent. That is intended: root stays a console account on the server machine, while the controller authenticates as the application account, which is scoped to db1 and to one client address.

Does the running flow need internet access?

No. Only the palette download needs it. Once installed, the MySQL node opens a connection to the server address configured in the node and nothing else, so a controller on an isolated plant network keeps logging as long as a route to the database server exists. Plan the firewall rule for that one address and port.

How do you confirm that every insert landed?

Compare counts in the mysql client. Run SELECT COUNT(*) FROM Drives and set it against the number of rows the flow sent: one per Inject press for the single-row test, one per array element for the PLC version, plus rows from earlier tests. A shortfall points at failed sends, and a Debug node on the MySQL node output shows the affected-row number for each message.

Keep reading

  • Troubleshooting

    Fix ECONNREFUSED when Node-RED connects to a remote SQL database

    ECONNREFUSED 127.0.0.1:3306 means the MySQL node dialed loopback on the machine running Node-RED, so the database computer was never contacted. Put the database computer's LAN address in the node's Host field, confirm MariaDB listens on that interface with TCP 3306 open, and create the account with the edge device's address as its host part.

    Edge computing and IIoT

  • How-to

    Log production data from a panel PC to SQL Server

    Run Node-RED on the panel PC, read the production values straight from the controller, and insert one row per event into SQL Server with the mssql-plus node. Keep the panel's CSV-plus-FTP file relay only as a fallback, block duplicates with a last-record check and a unique key, and expect about 86,400 rows, roughly 8.6 MB, per day at one record per second.

    Edge computing and IIoT

  • How-to

    How to query InfluxDB over MQTT with a bridge flow

    InfluxDB does not answer queries over MQTT: it serves them over its HTTP API. Put a bridge on the edge PC — a Node-RED flow subscribed to a request topic — that maps a validated, bounded request to a query against the bucket and publishes the result to a separate response topic, so request and reply never loop.

    Edge computing and IIoT

Why Ignition tag historian creates MySQL double columns