S7-300 to MySQL Database: Alarm Logging Architecture Guide

David Krause14 min read
S7-300SiemensTechnical Reference
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

1. Problem Definition: PLC-Side Alarm Logging to an External SQL Database

The classic integration question for a SIMATIC S7-300 station is how to persist alarm events — timestamp, alarm identifier, message text, and the operator that was logged on when the event was raised — into a relational database that the customer's downstream MySQL-based distribution system can consume. Typical specification language reads:

"The alarm system shall write alarms into a db file. This file shall be readable from MySQL applications. This file is to be accessible for the distributed alarm system where MySQL applications are used for distribution of alarms and for issuing of alarms through a pager system. File format and structure to be defined in cooperation with the customer."

The ambiguity in that text is the central engineering trap. "DB file" can mean either a SIMATIC data block inside the CPU or an external relational database. "Readable from MySQL" can mean "structured so that MySQL LOAD DATA INFILE can ingest it" or "queried live via SQL". The architecture that solves one interpretation fails the other.

Before any code is written on the CPU 315-2 DP, the integration engineer must resolve the following with the customer:

  • Pull (SCADA polls the PLC) vs. push (PLC/SCADA writes actively).
  • Online SQL connection vs. file-based ingestion.
  • Alarm bit granularity (only edges) vs. full message archive (every state change).
  • Identity of the logged-on user (HMI side vs. central authentication).
  • Acceptable latency for pager dispatch.

2. Architecture Overview: Why the S7-300 Cannot Talk to MySQL Directly

A CPU 315-2 DP (typical order number 6ES7315-2AG10-0AB0 with firmware V2.x or 6ES7315-2EH13-0AB0 V3.x) executes STEP 7 V5.x programs. Its communication stack — loaded into the CPU itself or off-loaded to the CP 343-1 (6GK7343-1EX30-0XE0 or 6GK7343-1CX10-0XE0) — supports ISO-on-TCP (RFC1006), TCP, UDP, S7 communication, and PROFINET. None of these transport layers map onto the MySQL wire protocol (a TCP-based request/response protocol that begins with a server greeting packet, a client authentication handshake, and a query/result exchange).

The engineering reality that Siemens officially confirms is that there is no native library, no system function block, and no firmware feature on the S7-300 CPU that opens a TCP socket, performs a MySQL handshake, and executes INSERT INTO alarms .... The CPU has neither an ODBC driver, a TLS stack suitable for MySQL 8.x caching_sha2_password authentication, nor a file system on which to stage a temporary SQL script. Approaches that propose this directly (videos, marketing demos, third-party claims) are either using a hidden PC runtime, a CP with embedded web server masquerading as a database, or are simply incorrect.

For comparison, the Wago 750-8xx PFC and Beckhoff CX/TwinCAT controllers do expose ODBC/SQL connectivity from the controller itself, but for Siemens the equivalent functionality is delegated to a Windows-based runtime component. This is why the practical architectures in Sections 4–7 always include a PC or panel PC with a Windows / WinCC runtime.

Architectural rule of thumb: The PLC raises alarm bits, timestamps them, and packs them into an S7 data block. A Windows-side component (WinCC RT, WinCC Flexible RT, a panel with logging, or a third-party OPC/DA bridge) is the only entity that owns a TCP socket to the MySQL server. Treat any proposal that places the MySQL client inside the CPU as a scope and cost red flag.

3. Hardware Reference: CPU 315-2 DP, CP 343-1, and Panel Options

The three building blocks most often quoted in this integration are listed below. Exact catalog numbers matter for spare-part compatibility, firmware matching, and STEP 7 / NCM PC configuration.

Component Order Number Key Specs Role in Alarm Logging
CPU 315-2 DP 6ES7315-2AG10-0AB0 (FW 2.x) or 6ES7315-2EH13-0AB0 (FW 3.x) 384 KB work memory, 1024 DI / 1024 DO / 256 AI / 256 AO; bit/integer/float/REAL; integrated MPI/DP interface Source of alarm bits and the alarm FIFO data block
CP 343-1 Lean 6GK7343-1CX10-0XE0 10/100 Mbit, TCP/UDP/ISO-on-TCP, S7 comm, max 4 connections (Lean) / 8 (Advanced), PROFINET IO controller Ethernet uplink if the CPU's PN port is occupied
CP 343-1 Advanced 6GK7343-1GX30-0XE0 (later -EX30) Adds FTP, HTTP, e-mail, integrated firewall, IP access lists Recommended when CSV files must be FTP-pushed to a server
TP 177B 6" color PN/DP 6AV6 642-0BA01-1AX1 WinCC Flexible 2008 SP3, 32 KB recipe memory, alarm buffer ~ 256 messages, USB stick slot Local alarm display; limited CSV export; no scripting
TP 270 10" 6AV6 545-0BA15-2AX0 ProTool/Pro RT, Windows CE, large alarm buffer, file system on PC card CSV export via file system, then FTP/HTTP push
OP 270 10" 6AV6 545-0BC15-2AX0 Same as TP270 but operator-only (no control) Used in legacy alarm loggers
WinCC Flexible Runtime (PC RT) 6AV6613-1BA01-1CA0 (128 PowerTags) + 6AV6613-2FA01-1CA0 (Archives option) Windows XP/7/10, ODBC logging, multi-station Direct ODBC bridge to MySQL when PC budget allows

The CP 343-1 Advanced variant is the one that enables an FTP client inside the CP itself, which is occasionally used to push a CSV file to a Windows share or directly to a MySQL host's LOAD DATA staging directory. The Lean variant cannot do this.

4. Approach 1 — HMI Panel with CSV Logging to External Storage

The smallest bill of materials that satisfies "alarms written to a file readable by MySQL" without introducing a new PC is:

  1. Raise alarm bits in the STEP 7 program on the CPU 315-2 DP. Use SFB 35 "ALARM" (for S7-300, classic) or configure a message-capable DB with SFC 17/18 for alarm_S/Q. Populate message text, associated value (e.g., tag value), and acknowledge state.
  2. Configure a TP 177B (or larger TP/OP) with WinCC Flexible 2008 SP3 to archive alarms. On the TP 177B the alarm buffer is internal; export to USB stick is possible only via the recipe/audit trail mechanism, not as a streaming CSV. For continuous CSV export, use a TP 270 / OP 270 with a PC card slot, or move to Approach 2.
  3. On the panel side, set the alarm log path to the PC card (e.g., \Storage Card\Alarms\alarms.csv). The panel writes one line per event.
  4. On the MySQL host, run a small watcher (a cron job, a Delphi/Visual Basic service, a Python daemon, or a PHP script) that periodically reads new CSV rows and issues LOAD DATA LOCAL INFILE '/var/lib/mysql/staging/alarms.csv' INTO TABLE alarms FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';.

The TP 177B is frequently proposed because it is small and inexpensive, but its CSV-export capability is limited: it supports logon audit trails and recipes as file exports, not continuous alarm archives. If the spec is firm on CSV, the TP 270 / OP 270 or a Panel PC with WinCC Flexible RT is the correct choice.

A TP 177B cannot host VBScript loops or schedule periodic file writes — the only scripting it supports is local function calls inside a screen. Treat any documentation that claims "TP 177B CSV file logging to network share" as either outdated marketing copy or referring to a specific recipe-export workflow, not a continuous alarm archive.

5. Approach 2 — WinCC Flexible RT on a Panel PC with ODBC/MySQL Logging

This is the most direct path to "MySQL readable database" because the panel PC is the database client.

  1. Install WinCC Flexible Runtime (PC) on a SIMATIC Panel PC, an IPC227G, or a generic industrial PC in the cabinet. Use at least the 128-PowerTag license (6AV6613-1BA01-1CA0) and the Archives option (6AV6613-2FA01-1CA0).
  2. In the WinCC Flexible project, define a tag-based alarm log. Enable the "Database" storage option in the alarm log configuration; WinCC Flexible RT uses a Microsoft Access / SQL Server Express Jet-style database via ODBC.
  3. Install the MySQL ODBC driver (Connector/ODBC 8.x, ANSI or Unicode variant). Create a System DSN MySQL_AlarmLog pointing at the MySQL server, the target schema (e.g., scada_alarms), and the destination table.
  4. In the alarm log settings, choose "Connect to database via ODBC". Map the archive fields:
WinCC Archive Column MySQL Column Type Notes
MsgNr msg_nr INT UNSIGNED Configured message number in WinCC
TimeStamp (ms since 01.01.1990) evt_time DATETIME(3) Convert from Windows FILETIME / ms epoch
Status evt_state TINYINT 1=Came, 2=Went, 3=Ack
Text msg_text VARCHAR(255) Multi-language text per configured language
User user_id VARCHAR(64) From WinCC user administration
Tag value tag_value FLOAT/DOUBLE Optional associated process value

WinCC Flexible RT writes each new alarm row to the configured ODBC DSN immediately on receipt. The MySQL host then distributes alarms to its pager subsystem independently. Compared to the CSV approach, latency drops from "next polling cycle" to "sub-second", at the cost of an industrial PC.

Cost-wise, a Panel PC 677 with WinCC Flex RT 128 + Archives lands well below the cost of a complete SCADA upgrade; this is the architecture to recommend when the customer insists on a live SQL database.

6. Approach 3 — OPC DA / OPC UA Bridge Architecture

For larger plants where a SCADA already exists (WinCC v7, WinCC Professional TIA Portal, Ignition, FactoryTalk, Citect), the canonical Siemens path is OPC rather than direct ODBC.

  1. Install SIMATIC Net PC Software (6GK1704-1LW08-3AA0 for OPC Server + S7-300 driver). This provides an OPC DA 2.05a / 3.0 server that the CPU 315-2 DP and CP 343-1 address via the S7 protocol.
  2. Configure an S7 connection in SIMATIC Net with the CP 343-1 IP address, the rack/slot of the CPU (rack 0, slot 2 for a CPU 315-2 DP), and the local TSAP (typically 01.01).
  3. Expose the alarm DB tags as OPC items. For alarm bits stored as a DWORD in DB200, the OPC path is S7:[S7 connection_1]DB200,DBW0.
  4. Use an OPC-to-MySQL bridge on the SCADA server. Common choices are:
  • Kepware IoT Gateway with the Historian plugin, posting JSON to a REST endpoint that the MySQL host turns into rows.
  • Inductive Automation Ignition with the Siemens driver and the MySQL JDBC database logger — a modern, widely deployed option.
  • Open-source Python: OpenOPC + mysql-connector-python running as a Windows service for small installations.

OPC UA (with a CP 343-1 Advanced or a CP 1543-1) eliminates the COM/DCOM dependency of OPC DA and traverses firewalls cleanly. The same bridge pattern holds.

7. Approach 4 — Third-Party SCADA / Soft-PLC Bridges

Several soft-logic and SCADA packages make the S7-300 → MySQL hop trivial because their data logging layer is a first-class feature:

Product S7-300 Driver MySQL Sink Notes
Ignition 8.x (Inductive Automation) Built-in Siemens driver JDBC to any RDBMS Tag history module writes directly to MySQL
WinCC Professional (TIA Portal) Native S7-1200/1500; S7-300 via Net/S7 Via SQL connector since V15.1 Requires WinCC RT/PC
AdvancedHMI / EasyOPC LibNoDave / Sharp7 Custom .NET code Free but DIY
Node-RED + node-red-contrib-s7 + node-red-node-mysql S7comm over ISO-on-TCP MySQL node Lightweight; use industrial fan-less PC

For the original poster's "not a very big application" constraint, Node-RED running on a fan-less industrial PC adjacent to the S7-300 station is often the lowest-cost live-SQL solution: it costs nothing in license fees, occupies a single DIN-mounted unit, and the SQL bridge is a 30-line flow.

8. CSV File Format Specification for MySQL Ingestion

If the customer accepts file-based ingestion (Approach 1), nail the CSV layout down in writing with them. A defensible default is:

"evt_time","msg_nr","state","priority","user_id","tag_value","msg_text"
"2025-01-15 14:32:07.123",4711,1,2,"erik.moller",87.42,"Tank T-101 level high"
"2025-01-15 14:32:18.405",4711,2,2,"erik.moller",82.10,"Tank T-101 level high"
"2025-01-15 14:32:18.901",4711,3,2,"erik.moller",82.10,"Tank T-101 level high"

The matching MySQL staging table and LOAD DATA call:

CREATE TABLE alarm_archive (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  evt_time DATETIME(3),
  msg_nr INT UNSIGNED,
  state TINYINT,
  priority TINYINT,
  user_id VARCHAR(64),
  tag_value DOUBLE,
  msg_text VARCHAR(255)
) ENGINE=InnoDB;

LOAD DATA INFILE '/srv/alarms/inbox/alarms.csv'
INTO TABLE alarm_archive
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

For a year of operation at one alarm per second this gives roughly 31.5 M rows — within comfortable MySQL territory provided the table is partitioned by month and indexed on evt_time.

State semantics are application-defined and must be agreed in writing. State 1 = Came, 2 = Went, 3 = Acknowledged is the de-facto standard in WinCC, but not in all HMI packages. Document the encoding in the FAT document and pin it in the S7 message configuration comment.

9. Implementation Procedure for the TP 177B → TP 270 → MySQL Path

The most common path the field report lands on is: TP 270 logs CSV, a service on the MySQL host ingests it. Concrete steps:

  1. In STEP 7 V5.5+, configure a message-capable data block on the CPU 315-2 DP. Use SFB 31 "NOTIFY_8P" for S7-300 message generation, or pass status changes to a TP/OP via SFC 107 "ALARM_D" for HMI display.
  2. In WinCC Flexible 2008 SP3, on the TP 270 project, define an Alarm Log. Set "Storage location" to \Storage Card\Logs\alarms.csv on the PC card. Set "Storage mode" to "Cyclic, segmented" with a segment size of 64 KB to avoid memory exhaustion.
  3. On the MySQL host (Linux), mount the network share \\TP270\\Alarms via Samba, or pull the file via FTP from the TP 270's FTP server (if licensed). WinCC Flexible can publish files via FTP only on OP/TP panels with the optional "Logging" license.
  4. Run a daemon (cron + mysqlimport) every 60 s that mvs new alarms_YYYYMMDD.csv files to /srv/alarms/staging/ and issues LOAD DATA LOCAL INFILE on each.
  5. Verify on a test bench by forcing 100 alarms from STEP 7 PLCSIM, watching the TP 270 log file grow, watching the staging directory pick it up, and confirming row counts in SELECT COUNT(*) FROM alarm_archive;.

10. Verification and Commissioning Checklist

Run through this matrix during the SAT (Site Acceptance Test):

Check Method Pass Criterion
Alarm bit → DB → HMI Force bit in PLCSIM, observe HMI message Message appears within 1 s with correct text
CSV file written Trigger 50 alarms, inspect PC card file 50 rows, header present, no truncation
CSV ingestion to MySQL Wait one polling cycle SELECT COUNT(*) FROM alarm_archive = 50 + prior
User identity propagated Log on as user "qa.lead", force alarm Row in alarm_archive has user_id='qa.lead'
Time synchronisation Compare S7 timestamp, HMI timestamp, MySQL NOW() Drift < 1 s after NTP on MySQL host
Latency, alarm to pager End-to-end timer < 5 s for ODBC path; < 90 s for CSV path
Storage growth Run for 72 h, measure archive size Within expected envelope (alarms/s × bytes/row)
Fault handling Disconnect MySQL host, force alarms, reconnect Bridge recovers; queued rows ingested; no duplicates

11. Troubleshooting Matrix

Symptom Likely Cause Corrective Action
No alarms in CSV file TP/OP "Logging" license not installed Install license key on the panel; verify in WinCC Flexible ES project properties
CSV file created but empty Alarm class on S7 side not configured to send to panel Check "Message configuration" in STEP 7; ensure DB is message-capable and bit address matches
MySQL rejects CSV rows Mismatched FIELDS TERMINATED BY / LINES TERMINATED BY Match WinCC export line ending (often \r\n for Windows-originated logs)
ODBC insert fails, WinCC Flex RT stops logging MySQL server unreachable or authentication rejected Verify MySQL 8.x default caching_sha2_password with ODBC 8.0.32+; otherwise ALTER USER ... IDENTIFIED WITH mysql_native_password
OPC DA: "Access Denied" from remote client DCOM not configured on Windows host Run dcomcnfg, grant OPCEnum launch and access rights to the SCADA service account
User ID always empty WinCC Flex RT cannot read HMI user name from S7 Use area pointer "User name" or a custom area pointer and bind to a tag
Times off by 1 hour DST transition on MySQL host Use UTC on both sides or set TIME_ZONE='+00:00' in MySQL

12. FAQ

Can a Siemens S7-300 (CPU 315-2 DP) send SQL queries directly to a MySQL database?

No. The CPU 315-2 DP executes STEP 7 code only; its firmware supports S7 communication, ISO-on-TCP, TCP, UDP, and PROFINET, none of which are the MySQL wire protocol. There is no SQL/ODBC library, no system function block, and no TCP socket abstraction in the S7-300 runtime that lets you issue INSERT statements. You must place a Windows-side runtime (WinCC Flex RT, WinCC, Ignition, or a Node-RED/Python bridge) between the PLC and the MySQL server.

Which Siemens HMI panels can continuously log alarms to a CSV file on a network share?

TP 270 / OP 270 / MP 270 panels running WinCC Flexible 2008 with the "Logging" license, and Panel PCs running WinCC Flexible Runtime, can write CSV alarm logs to a local storage card or network share. The TP 177B supports recipe and audit-trail file exports only and is not suitable for continuous alarm CSV logging.

What is the smallest bill of materials for live MySQL alarm logging from an S7-300?

An IPC227G or equivalent industrial PC with WinCC Flexible RT (128-PowerTag license 6AV6613-1BA01-1CA0 plus the Archives option 6AV6613-2FA01-1CA0), the MySQL Connector/ODBC 8.x driver, and a configured System DSN pointing to the MySQL target schema. The CP 343-1 Lean is sufficient for the S7 connection.

How do I propagate the logged-on user name from the HMI into the alarm row?

In WinCC Flexible, configure the area pointer "User name" or a custom area pointer bound to a tag of type STRING. The PLC reads this tag into a STRING DB field, and the alarm log entry carries it into the CSV/ODBC sink. On the MySQL side, store it in a VARCHAR(64) column. Without the area pointer, all rows will show the same generic operator.

Is OPC UA preferable to OPC DA for pushing S7-300 alarms to MySQL?

Yes, when a CP 343-1 Advanced or CP 1543-1 is available. OPC UA eliminates DCOM configuration on Windows, traverses firewalls cleanly, encrypts the channel, and is natively supported by modern SCADA bridges such as Ignition and Kepware. OPC DA still works and is cheaper on legacy hardware, but every remote OPC client requires DCOM hardening.

Back to blog