How-to
Configuring OPC UA to MySQL writes with a Template node
Short answer
A Template node between the OPC UA client and the MySQL node renders the counter into an INSERT statement on the topic property, the place the standard MySQL node looks for its query. The payload must carry only the scalar value, and the Now function stamps database execution time, not the OPC UA source timestamp.
On this page
- What goes between an OPC UA client and a MySQL node?
- What settings does the Template node need?
- Why must msg.payload hold only the number?
- Which message property does the MySQL node read?
- How do you prove one row is correct before logging continuously?
- Is Now() the OPC UA source timestamp?
- How do you replace interpolation with bound parameters?
- How many rows should a test produce, and what causes duplicates?
- Questions asked
Put a Template node between the OPC UA client and the MySQL node, and make it write the SQL statement to msg.topic. For a Prosys Simulation Server counter and a local MySQL database, the working template text is INSERT INTO test.prosys_table(Counter, Time) VALUES ('{{payload}}',Now());, with the Template node's output property changed to msg.topic, because the MySQL node reads its query from that property. Three checks decide whether the write is trustworthy: msg.payload must hold only the scalar value, the rendered statement must sit on the property your installed MySQL node actually reads, and the Time column must be allowed to mean database execution time, because Now() never copies the OPC UA source timestamp.
What goes between an OPC UA client and a MySQL node? #
A Template node goes between them: it takes the scalar value in msg.payload, renders it into an SQL INSERT statement, and outputs that statement on the property the MySQL node reads as its query. Node-RED only passes message objects from node to node; wired directly, the MySQL node receives a number where it expects SQL and writes nothing.
Check the message leaving the OPC UA client before touching either connection. Reinstalling the simulation server or recreating the database does not touch this conversion step, so it cannot fix it. The flow order is OPC UA client, then Template, then MySQL, with a Debug branch on the wire before the database while commissioning.
Decision: if the Debug node after the OPC UA client shows a value and the MySQL node writes nothing, the missing piece is this conversion node, not the server or the database.
What settings does the Template node need? #
Set the template text to INSERT INTO test.prosys_table(Counter, Time) VALUES ('{{payload}}',Now()); and change the output property from its default to msg.topic, so the rendered statement arrives where the standard MySQL node package expects its query. Build it in this order:
- Confirm the destination: database
test, tableprosys_table, columnsCounterandTime, and no third column that is mandatory and has no default, because one required column rejects the insert even when both supplied values are valid. - Add the Template node and paste the statement above as its text.
- Set the output property to
msg.topic; left at its default it would put the SQL string onmsg.payloadand leave the query property empty. - Wire OPC UA client to Template to MySQL, and keep the Debug node on the branch before the database.
The single quotes around {{payload}} make the rendered value an SQL string literal, which MySQL casts into a numeric Counter column. That cast is not validation: a quote inside the value ends the statement early, because a Template node renders text and does not escape it. Decision: use this node for the first proof, and gate anything unvalidated upstream of it.
Why must msg.payload hold only the number? #
Because the template prints whatever msg.payload contains: a bare number renders as a clean literal, while an object with status and timestamp fields renders as text MySQL cannot use, or breaks the statement outright. Put a Debug node directly after the OPC UA client and set it to display the complete message object, not just the payload.
The layout depends on the installed client node and its configuration: the value can arrive as a scalar in msg.payload or wrapped in an object that also carries OPC UA status and timestamps. If it is wrapped, extract the numeric field into msg.payload ahead of the Template node, and use the status field to drop bad samples before they become rows.
If no message arrives at all, the fault is on the acquisition side, meaning the endpoint, the security settings or the selected node, and no SQL formatting repairs it. Decision: interpolate only when the Debug output shows the bare scalar; otherwise extract first.
Which message property does the MySQL node read? #
The node-red-node-mysql package reads its query from msg.topic and returns the result set in msg.payload, which is exactly why the Template node's output property is set to msg.topic. Not every MySQL package agrees, since one alternative documents its query as an object on msg.payload, so open the installed node's help panel in the editor sidebar and match the property it names.
Put a second Debug node immediately before the MySQL node and confirm the statement occupies that exact property. SQL and value travel in the same message object, so also check the counter has neither overwritten the statement nor been dropped before the database node runs. If the node reports a refused connection rather than an SQL error, the flow is correct and the endpoint or firewall is at fault; the diagnosis is in fixing ECONNREFUSED when Node-RED connects to a remote SQL database.
Decision: the statement goes wherever that help panel says, and nowhere else.
How do you prove one row is correct before logging continuously? #
Send one known sample, read the rendered statement in the Debug output, then select the row back from the table and compare both columns against what you watched. Run it as a controlled sequence:
- Observe a known value at the OPC UA client's output; for example the counter reads 1234.
- Confirm the pre-database Debug node shows
INSERT INTO test.prosys_table(Counter, Time) VALUES ('1234',Now());, with the number matching and no object braces in the text. - Check both the normal output and the error output of the MySQL node.
- Read the row back, for example with
SELECT Counter, Time FROM test.prosys_table ORDER BY Time DESC LIMIT 5;. - Compare
Counterwith the observed value andTimewith the database clock, then repeat with several distinct values.
An SQL syntax error means the rendered statement is invalid, and a quote inside the payload is the usual cause. A rejected value means the payload's type does not fit the Counter column's definition, so compare them. No query reaching the database means the statement sits on the wrong property. Decision: enable continuous collection only after this test passes with several distinct values.
Is Now() the OPC UA source timestamp? #
No: Now() returns the time MySQL executes the statement, expressed in the session's time zone, so a queued or delayed message gets a row time later than the moment the sample was taken. OPC UA, standardized as IEC 62541, puts two timestamps on every data value, source and server, and the client can expose either in its message; insertion time is a third, separate time, and this template stores insertion time.
Decide what the Time column means before comparing it with other process records. If records must align to acquisition time, read the timestamp field the client message carries and write it explicitly instead of calling Now(). Also confirm the MySQL session time zone matches the PC and every consumer that compares records: stored times that later appear hours off usually trace to a UTC offset mismatch, covered in why a historian shows a real value hours off: check the UTC offset.
How do you replace interpolation with bound parameters? #
Keep the statement on msg.topic with ? placeholders and pass the value in msg.payload as an array, the pattern documented as msg.payload = [tag1, tag2]; with msg.topic = 'INSERT INTO MY_DB(Time, Psi) VALUES (?,?)';. For this table the parameterized pair is msg.topic = 'INSERT INTO test.prosys_table(Counter, Time) VALUES (?,Now());' and msg.payload = [1234];.
A Change node replaces the Template node: one rule sets the statement, a second sets the one-element array holding the value. The database then casts the bound value to the column type, and a quote inside the value can no longer terminate the statement. Decision: interpolation is fine for the first proof; binding is the form to leave running unattended.
How many rows should a test produce, and what causes duplicates? #
Fix the recording policy first: inserts triggered by subscription updates follow the value's changes, while a timer driving the write produces rows on a fixed period whether or not the value moved. The same policy choice appears whenever an OPC source feeds a relational store, as in logging PLC values from an OPC server into SQL Server.
Worked example, with example settings: the simulated counter increments once per second, the subscription's publishing interval is 1000 ms, and each update drives one insert. Over a 10-minute test the expected count is 10 min × 60 s/min ÷ 1 s per update = 600 rows. A COUNT(*) of 588 means 600 − 588 = 12 updates never became rows, so look for rejected samples or a brief connection loss before trusting the table.
Duplicates come from retries: an uncertain response, such as a timeout while waiting for the database, does not prove the insert failed, and a retry can add a second row with the same Counter value. If duplicates must be impossible for a monotonically increasing counter, a unique index on Counter turns a retried insert into a duplicate-key error instead of a second row. During a lost OPC UA connection the inserts stop instead, and the table gains a gap, the same failure shape covered in resolving connection loss gaps in an OPC UA historian.
Decision: count the rows a timed test should produce, then make the database reject what the recording policy forbids.
Questions asked
The row is written but Counter holds 0, what is wrong?
The payload rendered into the statement was not a bare number. Interpolating an object, or text carrying a stray quote, gives MySQL something it cannot cast: in strict SQL mode the insert fails, and outside strict mode a numeric column can end up storing zero. Print the complete message ahead of the Template node, extract the numeric field, and repeat the single-row test.
Can one statement write several OPC UA values into the same row?
Yes, when the values travel in one message. Give each value its own column and its own placeholder, keep the statement on the topic property, and pass the values in order as an array on the payload, the way the documented two-value example pairs a two-element array with two question-mark placeholders. Then run the same single-row verification.
The Debug sidebar shows the SQL but the MySQL node still sees no query, why?
Either a node between the Debug tap and the database overwrote the topic property, or the installed package reads a different property than the one you set. Move the Debug node directly onto the database node's input, open that node's help panel, put the statement on the exact property it names, and deploy again.
Does the same wiring work for SQL Server or another database?
The pattern transfers, the property names do not. Each database package documents where it expects the query, and some take an object on the payload instead of text on the topic property. Render the statement onto whatever property the installed node's help panel names, then prove it with one row before trusting continuous writes.